<div id="app"></div>
body {
background-color: #5225bd;
}
#app {
text-align: center;
}
p {
color: #FFF;
}
const ThemeContext = React.createContext('light')
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
theme: 'dark'
}
}
changeTheme() {
const actualTheme = this.state.theme
let newTheme
if (actualTheme == 'dark') {
newTheme = 'light'
} else {
newTheme = 'dark'
}
this.setState({
theme: newTheme
})
}
render() {
const { theme } = this.state
return (
<ThemeContext.Provider value={theme}>
<Button changeTheme={() => this.changeTheme()}/>
<Value />
</ThemeContext.Provider>
);
}
}
class Button extends React.Component {
render() {
return (
<button
onClick={() => this.props.changeTheme()}
>
Cambiar theme
</button>
)
}
}
class Value extends React.Component {
static contextType = ThemeContext;
render() {
return(
<div className="testContainer">
<p>Theme actual: <strong>{this.context}</strong></p>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"));
View Compiled
This Pen doesn't use any external CSS resources.