Skip to content

Instantly share code, notes, and snippets.

@themouette
Last active March 20, 2018 12:45
Show Gist options
  • Save themouette/fdf194e9d62c98ceccc65d1baebaaa52 to your computer and use it in GitHub Desktop.
Save themouette/fdf194e9d62c98ceccc65d1baebaaa52 to your computer and use it in GitHub Desktop.
react context
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