Skip to content

Instantly share code, notes, and snippets.

@AakashRaina
Created March 15, 2018 17:23
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 AakashRaina/531ba518c22bc25a229e67fa58936736 to your computer and use it in GitHub Desktop.
Save AakashRaina/531ba518c22bc25a229e67fa58936736 to your computer and use it in GitHub Desktop.
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
Copy link

Nice example, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment