react: all the context, no hot proptatoes - 401-advanced-javascript-aimurphy/seattle-javascript-401n13 GitHub Wiki
passing data down the tree without manually passing props at each level
You can pass to ANY descendant, not just direct parent to child and through and through
const MyContext = React.createContext(defaultValue);
...that can wrap around the app--any child inside the provider can access the data, no more passing down the props.
<MyContext.Provider value={/* some value */}>
you access the data in the child by creating a consumer.
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
the consumer tag refers to the provider, and whatever is inside of the consumer tag recieves the data from the provider. --@10:45 or so from wesbos
// Theme context, default to light theme
const ThemeContext = React.createContext('light');
// Signed-in user context
const UserContext = React.createContext({
name: 'Guest',
});
class App extends React.Component {
render() {
const {signedInUser, theme} = this.props;
// App component that provides initial context values
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={signedInUser}>
<Layout />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}
function Layout() {
return (
<div>
<Sidebar />
<Content />
</div>
);
}
// A component may consume multiple contexts
function Content() {
return (
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
);
}
this one is basically my husband's doppleganger.