Skip to content

Instantly share code, notes, and snippets.

@alexandrzavalii
Last active March 26, 2019 22:57
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 alexandrzavalii/8fd0fe01def1c94ecf172466404f3160 to your computer and use it in GitHub Desktop.
Save alexandrzavalii/8fd0fe01def1c94ecf172466404f3160 to your computer and use it in GitHub Desktop.
// create Context
const initialAmountOfLollipops = 0;
const LollipopContext = React.createContext(initialAmountOfLollipops);
/* ... Dumbo's parent Component */
const { lollipops } = this.state;
return (
// instead of passing lollipops to Dumbo, we pass it to the Context.Provider
<CandyContext.Provider value={lollipops}>
<Dumbo availableShoes={availableShoes} /* lollipops={lollipops} */ />
</CandyContext.Provider>
);
/* ... Dumbo Component */
render () {
const { availableShoes } = this.props;
const result = crazyComplexMethod(availableShoes);
return (
<div>
<FirstChild clothing={this.state.firstChild} />
</div>
);
}
// Use Consumer to read the value which we are passing from Provider
const FirstChild = props => (
<CandyContext.Consumer>
{value => (
<p>
I am John, and I am wearing {props.clothing} today.
{value ? "thanks for lollipop" : "I want lolipop"}
</p>
)}
</CandyContext.Consumer>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment