Browse Source
* Added an example showing how to update the context from inside a (deeply) nested component * Wrap comments * Wrap comments * Tweak wording * Prettier * Prettier * Typo: "funtion" -> "function"main
tjallingt
7 years ago
committed by
Alex Krolick
3 changed files with 76 additions and 0 deletions
@ -0,0 +1,45 @@ |
|||||
|
import {ThemeContext, themes} from './theme-context'; |
||||
|
import ThemeTogglerButton from './theme-toggler-button'; |
||||
|
|
||||
|
class App extends React.Component { |
||||
|
constructor(props) { |
||||
|
super(props); |
||||
|
|
||||
|
this.toggleTheme = () => { |
||||
|
this.setState(state => ({ |
||||
|
theme: |
||||
|
state.theme === themes.dark |
||||
|
? themes.light |
||||
|
: themes.dark, |
||||
|
})); |
||||
|
}; |
||||
|
|
||||
|
// highlight-range{1-2,5}
|
||||
|
// State also contains the updater function so it will
|
||||
|
// be passed down into the context provider
|
||||
|
this.state = { |
||||
|
theme: themes.light, |
||||
|
toggleTheme: this.toggleTheme, |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
render() { |
||||
|
// highlight-range{1,3}
|
||||
|
// The entire state is passed to the provider
|
||||
|
return ( |
||||
|
<ThemeContext.Provider value={this.state}> |
||||
|
<Content /> |
||||
|
</ThemeContext.Provider> |
||||
|
); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function Content() { |
||||
|
return ( |
||||
|
<div> |
||||
|
<ThemeTogglerButton /> |
||||
|
</div> |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
ReactDOM.render(<App />, document.root); |
@ -0,0 +1,20 @@ |
|||||
|
import {ThemeContext} from './theme-context'; |
||||
|
|
||||
|
function ThemeTogglerButton() { |
||||
|
// highlight-range{1-2,5}
|
||||
|
// The Theme Toggler Button receives not only the theme
|
||||
|
// but also a toggleTheme function from the context
|
||||
|
return ( |
||||
|
<ThemeContext.Consumer> |
||||
|
{({theme, toggleTheme}) => ( |
||||
|
<button |
||||
|
onClick={toggleTheme} |
||||
|
style={{backgroundColor: theme.background}}> |
||||
|
Toggle Theme |
||||
|
</button> |
||||
|
)} |
||||
|
</ThemeContext.Consumer> |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
export default ThemeTogglerButton; |
Loading…
Reference in new issue