Skip to content

Instantly share code, notes, and snippets.

@heldr
Created September 20, 2016 15:43
Show Gist options
  • Save heldr/4bf3bad3ab7a0e4a3de52d38e44fc0b4 to your computer and use it in GitHub Desktop.
Save heldr/4bf3bad3ab7a0e4a3de52d38e44fc0b4 to your computer and use it in GitHub Desktop.
Higher order component to toggle a prop value
/**
* 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