Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import React, { Component } from 'react';
// Create a context first of all //
const MyContext = React.createContext();
// Make a component class which returns the context using a provider //
class MyContextProvider extends Component {
constructor(props) {
super(props);
this.state = {
name: "Aakash",
like: "Write Code",
count:1
};
}
changeCount = () =>{
this.setState({count:this.state.count+1})
}
//using this.props.children because we want it to be accessible to every child //
render() {
return (
<div>
<MyContext.Provider value={[this.state.name,this.state.like,this.state.count,this.changeCount]}>
{this.props.children}
</MyContext.Provider>
</div>
)
}
}
// access context in a component using context.consumer.
// NOTE: It works using render props
class Component2 extends Component {
render() {
return (
<div>
<MyContext.Consumer>
{
(context) => (
<React.Fragment>
<p>My Name is:{context[0]}</p>
<p>I Like To:{context[1]}</p>
<p>Count:{context[2]}</p>
<button onClick={context[3]}>Click To Increase Count</button>
</React.Fragment>
)
}
</MyContext.Consumer>
</div>
)
}
}
class Component1 extends Component {
render() {
return (
<div>
<Component2 />
</div>
)
}
}
class App extends Component {
render() {
return (
// Enclose all your components which need access to context inside the provider //
<MyContextProvider>
<div>
<Component1 />
</div>
</MyContextProvider>
);
}
}
export default App;
@vshamgin

This comment has been minimized.

Copy link

vshamgin commented Jun 18, 2019

Nice example, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.