Last active
May 29, 2020 14:30
-
-
Save shotaK/49ca50b118ed22bc389bc231bcba9450 to your computer and use it in GitHub Desktop.
React Higher Order Component with props validation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component, PropTypes } from 'React'; | |
| export const Enhance = ComposedComponent => { | |
| class WrappedComponent extends Component { | |
| attachFunction() { | |
| ComposedComponent.attachFunction(); | |
| } | |
| render() { | |
| return <ComposedComponent {...this.props} additionalProps={this.state.additionalData} />; | |
| } | |
| } | |
| WrappedComponent.propTypes = { | |
| }; | |
| return WrappedComponent; | |
| }; | |
| export default Enhance; |
Cleaned up SBub's implementation for easier copy & paste cuz I just had to. Happy coding!
// Just assume LeftComponent & RightComponent output text in a <p> tag.
const LeftOrRight = (LeftComponent) => {
const EnhancedComponent = (props) => (
<Fragment>
{
(props.cond === true)
? (<LeftComponent {...props}>this component</LeftComponent>)
: (<RightComponent {...props}>OR this component</RightComponent>)
}
</Fragment>
)
EnhancedComponent.propTypes = {
cond: PropTypes.bool,
}
EnhancedComponent.defaultProps = {
cond: true,
}
return EnhancedComponent
}
export default LeftOrRight
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your implementation using stateless component
const Enhance = (args) => (WrappedComponent) => { const EnhancedComponent = props => ( <WrappedIconComponent {...props} withTypeCheck={true} /> ); EnhancedComponent.defaultProps = { }; EnhancedComponent.propTypes = { }; return EnhancedComponent; };