Browse Source

Updated multi-context example to show more indirection

main
Brian Vaughn 7 years ago
parent
commit
ef23c49e84
  1. 37
      examples/context/multiple-contexts.js

37
examples/context/multiple-contexts.js

@ -6,31 +6,40 @@ const ThemeContext = React.createContext('light');
// highlight-next-line // highlight-next-line
const UserContext = React.createContext(); const UserContext = React.createContext();
// An intermediate component that depends on both contexts
const Toolbar = props => {
// highlight-range{2-10}
return (
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
);
};
class App extends React.Component { class App extends React.Component {
static propTypes = { static propTypes = {
theme: PropTypes.string, theme: PropTypes.string,
signedInUser: PropTypes.shape({ signedInUser: PropTypes.shape({
id: number, id: number,
name: string, name: string,
avatar: string,
}), }),
}; };
render() { render() {
// highlight-range{9} const {signedInUser, theme} = this.props;
// App component that provides initial context values
// highlight-range{2-3,5-6}
return ( return (
<ThemeContext.Provider value={this.props.theme}> <ThemeContext.Provider value={theme}>
<UserContext.Provider <UserContext.Provider value={signedInUser}>
value={this.props.signedInUser}> <Toolbar />
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
</UserContext.Provider> </UserContext.Provider>
</ThemeContext.Provider> </ThemeContext.Provider>
); );

Loading…
Cancel
Save