Skip to content

Instantly share code, notes, and snippets.

@sineau
Created July 25, 2019 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sineau/785629ac2ee219af38969b35b66e86bd to your computer and use it in GitHub Desktop.
Save sineau/785629ac2ee219af38969b35b66e86bd to your computer and use it in GitHub Desktop.
import React, { Component, createContext } from 'react';
import './App.css';
const themes = {
light: {
color: '#000000',
background: '#eeeeee',
},
dark: {
color: '#ffffff',
background: '#222222',
},
};
const TestContext = createContext({
theme: 'light',
toggleTheme: () => {},
});
const { Provider, Consumer } = TestContext;
class App extends Component {
constructor() {
super();
this.toggleTheme = () => {
console.log('toggle called')
this.setState((state) => {
const newTheme = state.theme === themes.dark ? themes.light : themes.dark
return { state, ...{ theme: newTheme }}
}, () => console.log(this.state))
}
this.state = {
theme: themes.dark,
toggleTheme: this.toggleTheme,
}
}
render() {
return (
<TestContext.Provider value={this.state}>
<Toolbar />
</TestContext.Provider>
);
}
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
)
}
class ThemedButton extends Component {
static contextType = TestContext;
render() {
return (
<>
<Button theme={this.context} />
<OtherButton />
</>
)
}
}
function Button({ theme }) {
return <button style={theme.theme}>yo</button>
}
function OtherButton() {
return (
<Consumer>
{
value => {
return <button onClick={value.toggleTheme} style={value.theme}>Toggle</button>
}
}
</Consumer>
)
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment