Skip to content

Instantly share code, notes, and snippets.

@hoangthau
Last active December 26, 2018 01:04
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 hoangthau/04101d2232d75771d5607e3df6b9c3c8 to your computer and use it in GitHub Desktop.
Save hoangthau/04101d2232d75771d5607e3df6b9c3c8 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
// đầu tiên tạo một context
const MyContext = React.createContext();
// Sau đó tạo một Context Provider
class MyProvider extends Component {
state = {
name: 'Dan',
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) => (
<React.Fragment>
<p>Age: {context.state.age}</p>
<p>Name: {context.state.name}</p>
<button onClick={context.growAYearOlder}>🍰🍥🎂</button>
</React.Fragment>
)}
</MyContext.Consumer>
</div>
)
}
}
class App extends Component {
render() {
return (
<MyProvider>
<div>
<p>This is a demo that we use Context API</p>
<Family />
</div>
</MyProvider>
);
}
}
export default App;
@hoangthau
Copy link
Author

create context

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment