Created
July 25, 2017 15:27
-
-
Save kykean/1115de7ed4a24bf3666fca8f5c60cd26 to your computer and use it in GitHub Desktop.
React - Function as a child component to share state between siblings
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 React, { Component } from 'react'; | |
import propTypes from 'PropTypes'; | |
import StateWrapper from './StateWrapper'; | |
import CompA from 'CompA'; | |
import CompB from 'CompB'; | |
import CompC from 'CompC'; | |
class MainPage extends Component { | |
render() { | |
//layout are determined by children | |
return ( | |
<StateWrapper> | |
{(state, updateState) => ( | |
<CompA {...state} updateCb={updateState} /> | |
<CompB {...state} updateCb={updateState} /> | |
<CompC styles={/*any styles here*/} {...state} updateCb={updateState} /> | |
)} | |
</StateWrapper> | |
); | |
} | |
} |
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 React, { Component } from 'react'; | |
import propTypes from 'PropTypes'; | |
class StateWrapper extends Component { | |
constructor(props) { | |
this.state = {}; | |
this.updateState = this.updateState.bind(this); | |
} | |
//....some code goes here | |
updateState(nextState) { | |
//some logic goes here... | |
//...this.setState(...) | |
} | |
shouldCOmponentUpdate(nextProps, nextState) { | |
//keep state object shallow so its easy to compare. | |
} | |
render() { | |
return ( | |
<div> | |
{this.props.children(this.state, this.updateState)} | |
</div> | |
); | |
} | |
} | |
StateWrapper.propTypes = { | |
children: React.PropTypes.func.isRequired | |
} | |
export default StateWrapper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment