Skip to content

Instantly share code, notes, and snippets.

@danielsmykowski1
Last active December 1, 2019 13:12
Show Gist options
  • Save danielsmykowski1/c22218af30eb49b79f919faea1532a53 to your computer and use it in GitHub Desktop.
Save danielsmykowski1/c22218af30eb49b79f919faea1532a53 to your computer and use it in GitHub Desktop.
Code samples showing how to use React context
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
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
export const ThemeContext = React.createContext(
theme: themes.dark, // default value
toggleTheme: () => {},
);
import {ThemeContext} from './theme-context';
function ThemeTogglerButton() {
// 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;
import {ThemeContext} from './theme-context';
class ThemedButton extends React.Component {
render() {
let props = this.props;
let theme = this.context.theme;
return (
<button
{...props}
style={{backgroundColor: theme.background}}
/>
);
}
}
ThemedButton.contextType = ThemeContext;
export default ThemedButton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment