Last active
December 1, 2019 13:12
-
-
Save danielsmykowski1/c22218af30eb49b79f919faea1532a53 to your computer and use it in GitHub Desktop.
Code samples showing how to use React context
This file contains 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'; | |
import ThemeTogglerButton from './theme-toggler-button'; | |
// An intermediate component that uses the ThemedButton | |
function Toolbar(props) { | |
return ( | |
<ThemedButton onClick={props.changeTheme}> | |
Change Theme | |
</ThemedButton> | |
); | |
} | |
function Content() { | |
return ( | |
<div> | |
<ThemeTogglerButton /> | |
</div> | |
); | |
} | |
class Page extends React.Component { | |
constructor(props) { | |
super(props); | |
this.toggleTheme = () => { | |
this.setState(state => ({ | |
theme: | |
state.theme === themes.dark | |
? themes.light | |
: themes.dark, | |
})); | |
}; | |
// 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() { | |
// The ThemedButton button inside the ThemeProvider | |
// uses the theme from state while the one outside uses | |
// the default dark theme | |
return ( | |
<div class="page"> | |
<ThemeContext.Provider value={this.state}> | |
<Toolbar changeTheme={this.toggleTheme} /> | |
</ThemeContext.Provider> | |
<ThemeContext.Provider value={this.state}> | |
<Content /> | |
</ThemeContext.Provider> | |
<Section> | |
<ThemedButton /> | |
</Section> | |
</div> | |
); | |
} | |
} | |
export default Page |
This file contains 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( | |
theme: themes.dark, // default value | |
toggleTheme: () => {}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment