Last active
October 24, 2018 15:19
-
-
Save hypervillain/7db055cc8f2088c8c1124b8d643d6f3f to your computer and use it in GitHub Desktop.
A generic React component that renders its state and setState as props
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 { 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