Created
March 15, 2018 17:23
-
-
Save AakashRaina/531ba518c22bc25a229e67fa58936736 to your computer and use it in GitHub Desktop.
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'; | |
// 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice example, thanks!