Last active
July 18, 2018 08:04
-
-
Save reaktivo/466d6404d8b70654e7a0ad89086db3e3 to your computer and use it in GitHub Desktop.
Render Children with State Handlers
This file contains hidden or 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
import withStateHandlers from 'withStateHandlers'; | |
const initialState = { | |
value: '', | |
} | |
const handlersFactory = ({ props, state, setState }) => { | |
return { | |
setValue(value) { | |
setState({ value }); | |
} | |
} | |
} | |
const State = withStateHandlers({ initialState, handlersFactory }); | |
export default props => ( | |
<State> | |
{({ value }) => <input type="text" value={value} onChange={setValue} />} | |
</State> | |
); |
This file contains hidden or 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
import { PureComponent } from 'react'; | |
import PropTypes from 'prop-types'; | |
export default function withStateHandlers({ | |
initialState, | |
defaultProps, | |
handlersFactory, | |
}) { | |
return class WithStateHandlers extends PureComponent { | |
static propTypes = { | |
children: PropTypes.func, | |
}; | |
static defaultProps = defaultProps; | |
state = initialState; | |
setState = this.setState.bind(this); | |
render() { | |
this.handlers = handlersFactory({ | |
props: this.props, | |
setState: this.setState, | |
state: this.state, | |
}); | |
return this.props.children({ | |
setState: this.setState, | |
...this.state, | |
...this.handlers, | |
}); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment