Skip to content

Instantly share code, notes, and snippets.

@Palatnyi
Created June 10, 2018 13:35
Show Gist options
  • Save Palatnyi/167585e753f58186c7cd85713edeb644 to your computer and use it in GitHub Desktop.
Save Palatnyi/167585e753f58186c7cd85713edeb644 to your computer and use it in GitHub Desktop.
const withToggle = (initialState = {}) => (BaseComponent) => {
class WithHandlers extends React.Component {
constructor(props) {
super(props)
const initialStateKeys = Object.keys(initialState)
if (initialStateKeys.length) {
this.stateUpdaters = initialStateKeys.reduce((acc, value) => {
acc[`${value}Updater`] = () => (this.setState({ [value]: !this.state[value] }))
return acc
}, {})
}
this.state = { ...initialState }
}
render = () => <BaseComponent {...this.props} {...this.state} {...this.stateUpdaters} />
}
return WithHandlers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment