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
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 {
static propTypes = {
theme: PropTypes.string,
signedInUser: PropTypes.shape({
id: number,
name: string,
avatar: string,
}),
};
render() {
// highlight-range{9}
const {signedInUser, theme} = this.props;
// App component that provides initial context values
// highlight-range{2-3,5-6}
return (
<ThemeContext.Provider value={this.props.theme}>
<UserContext.Provider
value={this.props.signedInUser}>
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={signedInUser}>
<Toolbar />
</UserContext.Provider>
</ThemeContext.Provider>
);

Loading…
Cancel
Save