Last active
August 18, 2017 13:31
-
-
Save EloB/98795dd8f48c7c336f9fe58562a70c9c to your computer and use it in GitHub Desktop.
withHandlers example hoc
This file contains 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
class Button extends Component { | |
handleClick = (event) => { | |
const { onClick, test } = this.props; | |
if (onClick) onClick(event, test) | |
}; | |
render() { | |
return <button onClick={this.handleClick} />; | |
} | |
} | |
const withHandlers = handlers => ComposedComponent => class withHandlers extends Component { | |
static displayName = `withHandlers(${ComposedComponent.displayName || ComposedComponent.name})`; | |
state = {}; | |
componentWillMount() { | |
this.setState(Object.keys(handlers).reduce((obj, propName) => { | |
const handle = handlers[propName]; | |
obj[propName] = (...args) => { | |
handle(this.props)(...args); | |
}; | |
return obj; | |
}, {})); | |
} | |
render() { | |
return <ComposedComponent {...this.state} {...this.props} />; | |
} | |
} | |
const DumbButton = props => ( | |
<button {...props} /> | |
); | |
const SmartButton = withHandlers({ | |
onClick: ({ onClick, test }) => event => { | |
if (onClick) onClick(event, test); | |
}, | |
})(DumbButton); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haven't tested the code so I might be typos and bugs...