Skip to content

Instantly share code, notes, and snippets.

@olivierlesnicki
Created March 18, 2017 21:25
Show Gist options
  • Save olivierlesnicki/88a2b027b0a0358714c757d15816317c to your computer and use it in GitHub Desktop.
Save olivierlesnicki/88a2b027b0a0358714c757d15816317c to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
const Stateful = fn => {
return class Stateful extends Component {
constructor() {
super(...arguments);
this.component = this.component.bind(this);
this.state = {};
}
component(callback) {
return (...args) => {
return Promise
.resolve(callback.call(null, this.props, this.state, ...args))
.then(newState => {
this.setState(newState);
});
}
}
render() {
return fn.call(this.component, this.props, this.state);
}
}
};
function handleClick(props, state, event) {
if (event.button === 1) {
// Middle click resets state to zero
return { count: 0 };
}
if (props.onClick) {
props.onClick();
}
return { count: state ? state.count + 1 : 0 };
}
export default Stateful(function Counter(props, state) {
return (
<div>
Clicked {state ? state.count : 0} times
<button onClick={this(handleClick)} style={{ width: props.width }} />
</div>
);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment