Last active
April 28, 2018 19:15
-
-
Save aquiseb/c26c4bfa716521da0745225b31db4e70 to your computer and use it in GitHub Desktop.
React 16.3 Context example
This file contains 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 { render } from "react-dom"; | |
const PostContext = React.createContext(); | |
class PostProvider extends Component { | |
state = { | |
review: "bad" | |
}; | |
render() { | |
return ( | |
<PostContext.Provider | |
value={{ | |
state: this.state, | |
changeReview: () => | |
this.setState({ | |
review: "good" | |
}) | |
}} | |
> | |
{this.props.children} | |
</PostContext.Provider> | |
); | |
} | |
} | |
const PostConsumer = props => { | |
return ( | |
<PostContext.Consumer> | |
{context => ( | |
<React.Fragment> | |
<p>This post is <strong>{context.state.review}</strong></p> | |
<button onClick={context.changeReview}>Change review</button> | |
</React.Fragment> | |
)} | |
</PostContext.Consumer> | |
); | |
}; | |
// PostConsumer can be deeply nested | |
// without doing "props drilling" | |
const DummyComponent = () => { | |
return <PostConsumer />; | |
}; | |
export default class Index extends Component { | |
render() { | |
return ( | |
<PostProvider> | |
<DummyComponent /> | |
</PostProvider> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment