Skip to content

Instantly share code, notes, and snippets.

@farmasek
Created March 25, 2018 16:24
Show Gist options
  • Save farmasek/d3d7b4a3d7163b5712330f8a75ede337 to your computer and use it in GitHub Desktop.
Save farmasek/d3d7b4a3d7163b5712330f8a75ede337 to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { render } from 'react-dom';
const ThemeContext = React.createContext({
color: 'red',
backgroundColor: 'blue',
});
class ThemeProvider extends React.Component {
state = {
theme: {
color: 'red',
backgroundColor: 'yellow',
},
};
switchTheme = () =>
this.setState(({ theme }) => ({
theme: {
color: theme.color === 'red' ? 'blue' : 'red',
backgroundColor:
theme.backgroundColor === 'yellow' ? 'green' : 'yellow',
},
}));
render() {
return (
<ThemeContext.Provider value={this.state.theme}>
<button onClick={this.switchTheme}>Change colors</button>
{this.props.children}
</ThemeContext.Provider>
);
}
}
class Title extends React.Component {
render() {
return (
<ThemeContext.Consumer>
{value => <h1 style={{ ...value }}>{this.props.children}</h1>}
</ThemeContext.Consumer>
);
}
}
const AppBody = () => (
<div>
<Title>Themed Title</Title> With additional text
</div>
);
const App = () => (
<ThemeProvider>
<AppBody />
</ThemeProvider>
);
render(<App />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment