Created
July 25, 2019 06:57
-
-
Save sineau/785629ac2ee219af38969b35b66e86bd to your computer and use it in GitHub Desktop.
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 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