Skip to content

Instantly share code, notes, and snippets.

@kykean
Created July 25, 2017 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kykean/1115de7ed4a24bf3666fca8f5c60cd26 to your computer and use it in GitHub Desktop.
Save kykean/1115de7ed4a24bf3666fca8f5c60cd26 to your computer and use it in GitHub Desktop.
React - Function as a child component to share state between siblings
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>
);
}
}
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