Skip to content

Instantly share code, notes, and snippets.

@aryanshridhar
Created April 12, 2020 07:18
Show Gist options
  • Save aryanshridhar/bf55cac0812d432cd571283551e59bf4 to your computer and use it in GitHub Desktop.
Save aryanshridhar/bf55cac0812d432cd571283551e59bf4 to your computer and use it in GitHub Desktop.
Context Api in React.js
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>
)
}
}
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>
)
}
}
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