Skip to content

Instantly share code, notes, and snippets.

@gaearon
Created April 23, 2015 16:57
Show Gist options
  • Save gaearon/e31f2406e07952691f27 to your computer and use it in GitHub Desktop.
Save gaearon/e31f2406e07952691f27 to your computer and use it in GitHub Desktop.
Stateful.js
import React, { Component } from 'react';
// Usage:
//
// @Stateful({
// initialize(props) {
// return {
// count: 0
// };
// },
// reducers: {
// increment(props, state) {
// return {
// count: state.count + 1
// };
// }
// }
// })
// class Counter {
// static propTypes = {
// count: PropTypes.number.isRequired,
// increment: PropTypes.func.isRequired
// };
// render() {
// const { count, increment } = this.props;
// return (
// <button onClick={increment}>
// Pressed {count} times.
// </button>
// )
// }
// }
export default function Stateful({ initialize, reducers }) {
return DecoratedComponent => class StateContainer extends Component {
constructor(props) {
super(props);
this.state = initialize(props);
this.reducers = {};
Object.keys(reducers).forEach(key => {
this.reducers[key] = (...args) => {
const nextState = reducers[key](this.props, this.state, ...args);
this.setState(nextState);
}
});
}
render() {
return <DecoratedComponent {...this.props}
{...this.state}
{...this.reducers} />;
}
}
}
@gaearon
Copy link
Author

gaearon commented Apr 25, 2015

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