Last active
March 20, 2018 12:45
-
-
Save themouette/fdf194e9d62c98ceccc65d1baebaaa52 to your computer and use it in GitHub Desktop.
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 React, { Fragment, Component, createContext } from 'react'; | |
import ReactDOM from 'react-dom'; | |
const ThemeContext = createContext('light'); | |
const ThemedItem = props => ( | |
<ThemeContext.Consumer>{ | |
(theme) => <p>{theme}</p> | |
}</ThemeContext.Consumer> | |
) | |
class App extends Component { | |
constructor() { | |
super(); | |
this.state = { | |
theme1: 'light', | |
theme2: 'dark', | |
}; | |
this.swap = this.swap.bind(this); | |
} | |
swap() { | |
this.setState({ | |
theme1: this.state.theme2, | |
theme2: this.state.theme1, | |
}); | |
} | |
render() { | |
return ( | |
<Fragment> | |
<ThemeContext.Provider value={this.state.theme1}> | |
<ThemedItem /> | |
</ThemeContext.Provider> | |
<ThemeContext.Provider value={this.state.theme2}> | |
<ThemedItem /> | |
</ThemeContext.Provider> | |
<button onClick={this.swap}>Swap</button> | |
</Fragment> | |
); | |
} | |
} | |
function run(mountNode) { | |
ReactDOM.render( | |
<App />, | |
mountNode | |
); | |
} | |
document.addEventListener('DOMContentLoaded', function() { | |
run(document.getElementById('app')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment