Created
September 20, 2016 15:43
-
-
Save heldr/4bf3bad3ab7a0e4a3de52d38e44fc0b4 to your computer and use it in GitHub Desktop.
Higher order component to toggle a prop value
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
/** | |
* Higher order component to toggle a prop value | |
* | |
* @see https://goo.gl/q7mQGm | |
* @function withToggle | |
* @returns Component | |
*/ | |
export default function withToggle(WrappedComponent, propName = 'bool') { | |
class WithToggle extends Component { | |
constructor(props, context) { | |
super(props, context); | |
this.state = { bool: props[propName] }; | |
this.onToggleBool = this.toggleBool.bind(this); | |
} | |
toggleBool() { | |
this.setState({ bool: !this.state.bool }) | |
} | |
render() { | |
// do not mutate props | |
const newProps = Object.assign({}, this.props, { | |
[`${propName}`]: this.state.bool, | |
toggle: this.onToggleBool | |
}); | |
return React.createElement(WrappedComponent, newProps); | |
} | |
} | |
WithToggle.defaultProps = { | |
[`${propName}`]: false | |
}; | |
WithToggle.propTypes = { | |
[`${propName}`]: React.PropTypes.bool | |
}; | |
return WithToggle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment