Created
March 11, 2018 14:53
-
-
Save MicroBenz/b1ad4b1843f4f3bdb991c8ac71dbb029 to your computer and use it in GitHub Desktop.
React Context
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
// 1.Create context via createContext() | |
import React, { createContext } from 'react'; | |
const MediaPathContext = createContext({ | |
prefixPath: 'cloudfront-production' // as default | |
}); | |
// 2.Use "Provider" at root component to make any sub-tree component can consume context data | |
const isProduction = process.env.NODE_ENV === 'production'; | |
const mediaPath = isProduction ? 'cloudfront-production' : 'cloudfront-development'; | |
class App extends React.Component { | |
render() { | |
return ( | |
<MediaPathContext.Provider value={{ prefixPath: mediaPath }}> | |
<Nav /> | |
<Main /> | |
<Footer /> | |
</MediaPathContext.Provider> | |
); | |
} | |
} | |
// 3.In component that want to use context data just put it as a child of "Consumer" to consume it | |
const Main = () => ( | |
<MediaPathContext.Consumer> | |
{(context) => ( | |
<img src={`${context.prefixPath}/landing.jpg`} /> | |
)} | |
</MediaPathContext.Consumer> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment