Skip to content

Instantly share code, notes, and snippets.

@faisalhmohd
Last active January 12, 2019 13:55
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 faisalhmohd/d565700b0ff7b2cadf6b3b1a0318cd94 to your computer and use it in GitHub Desktop.
Save faisalhmohd/d565700b0ff7b2cadf6b3b1a0318cd94 to your computer and use it in GitHub Desktop.
React v16 Context API Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://fb.me/react-with-addons-15.1.0.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
const AppWideContext = React.createContext();
class AppContext extends React.Component {
constructor(props) {
super(props);
this.modifyContext = this.modifyContext.bind(this);
this.state = {
modifyContext: this.modifyContext,
contextData: {
propOne: 'initialValue',
}
};
}
modifyContext(contextData) {
console.log('modifyContext');
this.setState({ contextData: contextData });
}
render() {
const { children } = this.props;
console.log('AppContext:Render');
return (
<AppWideContext.Provider value={this.state}>
{ children }
</AppWideContext.Provider>
);
}
}
function ComponentTwoChild() {
console.log('ComponentTwoChild:Render');
return (
<div>
<AppWideContext.Consumer>
{({ contextData }) => {
console.log('ComponentTwoChild:Consumer');
return (
<div>{contextData.propOne}</div>
)}}
</AppWideContext.Consumer>
<div>Second Child Component</div>
</div>
);
}
function ComponentOneChild() {
console.log('ComponentOneChild:Render');
return (
<div>
First Child Component
<AppWideContext.Consumer>
{({ modifyContext }) => {
console.log('ComponentOneChild:Consumer');
return (
<span onClick={() => modifyContext({ propOne: 'modifiedValue' })}>Change Context</span>
)}}
</AppWideContext.Consumer>
</div>
);
}
function ComponentOne() {
console.log('ComponentOne:Render');
return (
<div>
First Component
<ComponentOneChild />
</div>
);
}
function ComponentTwo() {
console.log('ComponentTwo:Render');
return (
<div>
Second Component
<ComponentTwoChild />
</div>
);
}
function MainApp() {
console.log('MainApp:Render');
return (
<AppContext>
<ComponentOne />
<br />
<ComponentTwo />
</AppContext>
);
}
ReactDOM.render(<MainApp />, document.querySelector("#app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment