Last active
July 6, 2018 06:11
-
-
Save ticidesign/e81f8f9af801dfe48e8d5643a88b79da to your computer and use it in GitHub Desktop.
React’s New Context API
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'; | |
const MyContext = React.createContext(); | |
class MyProvider extends Component { | |
state = { | |
name: 'Tici', | |
age: 100, | |
cool: true | |
} | |
render() { | |
return ( | |
<MyContext.Provider value={{ | |
state: this.state, | |
growOlder: () => this.setState({ | |
age: this.state.age + 1 | |
}) | |
}}> | |
{this.props.children} | |
</MyContext.Provider> | |
) | |
} | |
} | |
const Family = (props) => ( | |
<div className="family"> | |
<Person /> | |
</div> | |
) | |
class Person extends Component { | |
render(){ | |
return ( | |
<div className="person"> | |
<MyContext.Consumer> | |
{(context) => ( | |
<React.Fragment> | |
<p>My name is {context.state.name}</p> | |
<p>I am {context.state.age}</p> | |
<button onClick={context.growOlder}>🎂</button> | |
</React.Fragment> | |
)} | |
</MyContext.Consumer> | |
</div> | |
) | |
} | |
} | |
class App extends Component { | |
render() { | |
return ( | |
<MyProvider> | |
<div className="App"> | |
<p>I am an app</p> | |
<Family /> | |
</div> | |
</MyProvider> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment