Skip to content

Instantly share code, notes, and snippets.

@hypervillain
Last active October 24, 2018 15:19
Show Gist options
  • Save hypervillain/7db055cc8f2088c8c1124b8d643d6f3f to your computer and use it in GitHub Desktop.
Save hypervillain/7db055cc8f2088c8c1124b8d643d6f3f to your computer and use it in GitHub Desktop.
A generic React component that renders its state and setState as props
import { Component } from 'react';
import PropTypes from 'prop-types';
class ForwardState extends Component {
static propTypes = {
children: PropTypes.func.isRequired,
ComponentWrapper: PropTypes.string || PropTypes.node,
init: PropTypes.object, // eslint-disable-line react/forbid-prop-types
setStatePropName: PropTypes.string,
statePropName: PropTypes.string,
}
static defaultProps = {
ComponentWrapper: 'div',
init: null,
setStatePropName: 'setState',
statePropName: 'state',
};
constructor(props) {
super(props);
this.state = props.init || {};
this.setThisState = this.setThisState.bind(this);
}
setThisState(newState, cb) {
this.setState(newState, cb || null);
}
render() {
const {
children,
setStatePropName,
statePropName,
ComponentWrapper,
...rest
} = this.props;
return (
<ComponentWrapper {...rest}>
{children({
[statePropName]: this.state,
[setStatePropName]: this.setThisState,
})}
</ComponentWrapper>
);
}
}
ForwardState.displayName = 'ForwardState';
export default ForwardState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment