Skip to content

Instantly share code, notes, and snippets.

@imparvez
Created June 17, 2018 16:05
Show Gist options
  • Save imparvez/b4a14f7e5a418f85a3804ff44d05b27d to your computer and use it in GitHub Desktop.
Save imparvez/b4a14f7e5a418f85a3804ff44d05b27d to your computer and use it in GitHub Desktop.
React Context API 16.4
import React, { Component, Fragment } from 'react';
// first we'll create a new context
const MyContext = React.createContext();
// provider component where our data will live
class MyProvider extends Component{
state = {
name: 'Prazzy',
age: 30,
cool: true
}
render(){
return(
<MyContext.Provider value={{
state: this.state,
growAYearOlder: () => this.setState({
age: this.state.age + 1
})
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
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}>Click me</button>
</Fragment>
)}
</MyContext.Consumer>
</div>
)
}
}
const Family = (props) => (
<div className="family">
<Person />
</div>
);
class App extends Component {
render() {
return (
<MyProvider>
<div className="App">
<p>I'm 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