Created
November 5, 2018 11:03
-
-
Save jackinf/b90e01ebe4926dd25b9f3d8289c095e4 to your computer and use it in GitHub Desktop.
React context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ThemeContext, themes} from './theme-context'; | |
import ThemedButton from './themed-button'; | |
// An intermediate component that uses the ThemedButton | |
function Toolbar(props) { | |
return ( | |
<ThemedButton onClick={props.changeTheme}> | |
Change Theme | |
</ThemedButton> | |
); | |
} | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
theme: themes.light, | |
}; | |
this.toggleTheme = () => { | |
this.setState(state => ({ | |
theme: | |
state.theme === themes.dark | |
? themes.light | |
: themes.dark, | |
})); | |
}; | |
} | |
render() { | |
// The ThemedButton button inside the ThemeProvider | |
// uses the theme from state while the one outside uses | |
// the default dark theme | |
return ( | |
<Page> | |
<ThemeContext.Provider value={this.state.theme}> | |
<Toolbar changeTheme={this.toggleTheme} /> | |
</ThemeContext.Provider> | |
<Section> | |
<ThemedButton /> | |
</Section> | |
</Page> | |
); | |
} | |
} | |
ReactDOM.render(<App />, document.root); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const themes = { | |
light: { | |
foreground: '#000000', | |
background: '#eeeeee', | |
}, | |
dark: { | |
foreground: '#ffffff', | |
background: '#222222', | |
}, | |
}; | |
export const ThemeContext = React.createContext( | |
themes.dark // default value | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment