Skip to content

Instantly share code, notes, and snippets.

@aquiseb
Last active April 28, 2018 19:15
Show Gist options
  • Save aquiseb/c26c4bfa716521da0745225b31db4e70 to your computer and use it in GitHub Desktop.
Save aquiseb/c26c4bfa716521da0745225b31db4e70 to your computer and use it in GitHub Desktop.
React 16.3 Context example
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