Skip to content

Instantly share code, notes, and snippets.

@MicroBenz
Created March 11, 2018 14:53
Show Gist options
  • Save MicroBenz/b1ad4b1843f4f3bdb991c8ac71dbb029 to your computer and use it in GitHub Desktop.
Save MicroBenz/b1ad4b1843f4f3bdb991c8ac71dbb029 to your computer and use it in GitHub Desktop.
React Context
// 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