Skip to content

Instantly share code, notes, and snippets.

@anthonybrown
Last active May 8, 2018 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonybrown/ebf1bf87a3b82e405971df07bd8d2083 to your computer and use it in GitHub Desktop.
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
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