Last active
May 10, 2018 01:01
-
-
Save shrynx/5487d6acb8c2870238e65036a8b85a06 to your computer and use it in GitHub Desktop.
simple demo of react's context api
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
const CounterContext = React.createContext(0); | |
class CounterProvider extends React.Component { | |
state = { count: 0 }; | |
incrementCount = () => { | |
this.setState(({ count }) => ({ count: count + 1 })); | |
}; | |
componentDidMount() { | |
setInterval(this.incrementCount, 1000); | |
} | |
render() { | |
return ( | |
<CounterContext.Provider value={this.state.count}> | |
{this.props.children} | |
</CounterContext.Provider> | |
); | |
} | |
} | |
const DisplayCount = () => ( | |
<CounterContext.Consumer> | |
{value => <div>{value}</div>} | |
</CounterContext.Consumer> | |
); | |
class App extends React.Component { | |
render() { | |
return ( | |
<CounterProvider> | |
<div> | |
<DisplayCount /> | |
</div> | |
</CounterProvider> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment