Skip to content

Instantly share code, notes, and snippets.

@shotaK
Last active May 29, 2020 14:30
Show Gist options
  • Select an option

  • Save shotaK/49ca50b118ed22bc389bc231bcba9450 to your computer and use it in GitHub Desktop.

Select an option

Save shotaK/49ca50b118ed22bc389bc231bcba9450 to your computer and use it in GitHub Desktop.
React Higher Order Component with props validation.
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;
@mrpotatoes
Copy link

mrpotatoes commented Jun 27, 2018

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