Skip to content

Instantly share code, notes, and snippets.

@reaktivo
Last active July 18, 2018 08:04
Show Gist options
  • Save reaktivo/466d6404d8b70654e7a0ad89086db3e3 to your computer and use it in GitHub Desktop.
Save reaktivo/466d6404d8b70654e7a0ad89086db3e3 to your computer and use it in GitHub Desktop.
Render Children with State Handlers
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>
);
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