Skip to content

Instantly share code, notes, and snippets.

@EloB
Last active August 18, 2017 13:31
Show Gist options
  • Save EloB/98795dd8f48c7c336f9fe58562a70c9c to your computer and use it in GitHub Desktop.
Save EloB/98795dd8f48c7c336f9fe58562a70c9c to your computer and use it in GitHub Desktop.
withHandlers example hoc
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);
@EloB
Copy link
Author

EloB commented Aug 18, 2017

Haven't tested the code so I might be typos and bugs...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment