G
G
GreaterGlider2019-02-19 13:50:09
React
GreaterGlider, 2019-02-19 13:50:09

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>
        )
    }
}

When you click, the styles change to light, but when you click again, they don’t want to change to dark. The question is how to implement such behavior? And what is the best way to work with dynamic mutable styles in React?
Important addition: should work in IE at least version 11.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Wolf, 2019-02-19
@mannaro

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 question

Ask a Question

731 491 924 answers to any question