Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Created December 2, 2016 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvergnaud/fab50407b9e83acb4736eeebb8349466 to your computer and use it in GitHub Desktop.
Save gvergnaud/fab50407b9e83acb4736eeebb8349466 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import isEqual from 'lodash/fp/isEqual'
// let you inject local state to you component
const stateful = (mapPropsToInitialState = () => ({})) => Child => {
return class StateFul extends Component {
static displayName = `StateFul(${Child.displayName || Child.name})`
componentWillMount() {
this.state = mapPropsToInitialState(this.props)
}
render() {
return (
<Child
{...this.props}
{...Object.keys(this.state).reduce((acc, key) => ({
...acc,
[key]: {
value: this.state[key],
onChange: this[`_update${key}`] || (this[`_update${key}`] = v => this.setState({ [key]: v })),
}
}), {})} />
)
}
}
}
export default stateful
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment