Last active
April 10, 2018 20:48
-
-
Save tyler-dot-earth/9e6a732a7044526e37ce7c9faf6ad4be to your computer and use it in GitHub Desktop.
React 16.3 context example in ~30 lines of code.
This file contains hidden or 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
import * as React from 'react'; | |
import SomeContext from './SomeContext.jsx'; | |
const App = () => ( | |
<SomeContext.Provider value={{ foo: 'bar' }}> | |
<App /> | |
</SomeContext.Provider> | |
); | |
export default App; |
This file contains hidden or 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
import * as React from 'react'; | |
export const Context = React.createContext(); | |
export default { | |
Provider: Context.Provider, | |
Consumer: Context.Consumer, | |
}; |
This file contains hidden or 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
import * as React from 'react'; | |
import SomeContext from './SomeContext.jsx'; | |
// My parent (or grandparent, or great grandparent, etc) is App (which has Context.Provider). | |
const SomewhereDownApp = () => ( | |
<div> | |
<SomeContext.Consumer> | |
{context => ( | |
<p>Foo: {context.foo}</p> | |
)} | |
</SomeContext.Consumer> | |
</div> | |
); | |
export default SomewhereDownApp; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment