Last active
May 8, 2018 11:08
-
-
Save anthonybrown/ebf1bf87a3b82e405971df07bd8d2083 to your computer and use it in GitHub Desktop.
A simple example of how to use the Context API from Wes Bos
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, Fragment } from 'react' | |
// First make a new context | |
const MyContext = React.createContext() | |
// then create a provider Component | |
class MyProvider extends Component { | |
state = { | |
name: 'Tony', | |
age: 100, | |
cool: true, | |
} | |
render() { | |
return ( | |
<MyContext.Provider value={{ | |
state: this.state, | |
growAYearOlder: () => 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) => ( | |
<Fragment> | |
<p>Age: {context.state.age}</p> | |
<p>Name: {context.state.name}</p> | |
<button onClick={context.growAYearOlder}>🍰 🎂 🍥</button> | |
</Fragment> | |
)} | |
</MyContext.Consumer> | |
</div> | |
) | |
} | |
} | |
class App extends Component { | |
render() { | |
return ( | |
<MyProvider> | |
<div> | |
<p>I am the 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