Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
Add Comment
Please, Sign In to add comment