Created
April 12, 2020 07:18
-
-
Save aryanshridhar/bf55cac0812d432cd571283551e59bf4 to your computer and use it in GitHub Desktop.
Context Api in React.js
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' | |
import Child from './Child.js' | |
export const ContextApi = React.createContext(); | |
export default class App extends Component { | |
state = { | |
language : "Javascript", | |
Framework : 'React.js' | |
} | |
render() { | |
return ( | |
<div> | |
<ContextApi.Provider value = {this.state}> | |
<h1>Hello This is a context api from App.js</h1> | |
<Child/> | |
</ContextApi.Provider> | |
</div> | |
) | |
} | |
} | |
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' | |
import Grandchild from './Grandchild' | |
export default class Child extends Component { | |
render() { | |
return ( | |
<div> | |
<h2>In Users.js</h2> | |
<Grandchild/> | |
</div> | |
) | |
} | |
} |
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' | |
import { ContextApi } from './App.js' | |
import './App.js' | |
export default class Grandchild extends Component { | |
render() { | |
return ( | |
<div> | |
<ContextApi.Consumer> | |
{ | |
(data) => { // Use {data1,data2..} instead of data when sending multiple data | |
return ( | |
<div> | |
<h2>{data.language}</h2> | |
<h2>{data.Framework}</h2> | |
</div> | |
) | |
} | |
} | |
</ContextApi.Consumer> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment