Answer the question
In order to leave comments, you need to log in
How to make CSS theme switcher in React app?
Good day everyone!
There are two style sheets, a conditionally light theme and a dark theme. I wrote a component that loads a .css file on click:
class StyleSwitcher extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
}
this.handleOnClick = this.handleOnClick.bind(this);
}
handleOnClick(event) {
this.setState({checked: !this.state.checked});
if (!this.state.checked) {
import('./light.css')
} else {
import('./dark.css')
}
}
render() {
return (
<Fragment>
<input type="checkbox" onClick={this.handleOnClick}/>
</Fragment>
)
}
}
Answer the question
In order to leave comments, you need to log in
So you just have styles connected and not removed. Do it the old fashioned way with createElement('style') and then remove it when switching styles.
UPD May 13, 2019: in general, in React it is now customary to pass the theme from somewhere above (for example, using the context) and implement the style at the component level. Loading CSS directly looks like some kind of cruel crutch.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question