Skip to content

Instantly share code, notes, and snippets.

@ticidesign
Last active July 6, 2018 06:11
Show Gist options
  • Save ticidesign/e81f8f9af801dfe48e8d5643a88b79da to your computer and use it in GitHub Desktop.
Save ticidesign/e81f8f9af801dfe48e8d5643a88b79da to your computer and use it in GitHub Desktop.
React’s New Context API
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