简体   繁体   中英

Apply CSS theme based on react state

I have a REACT application (bootstrapped with create react app and react-bootstrap ) for which I am trying to add option to switch to DARK theme if user enabled this in his settings. I am storing the settings on server and fetching them into properties.

I have a separate stylesheet called dark.css where all my component styles are overriden.

dark.css (example):

#root {
  background-color: var(--dark);
  color: var(--light)
}

.card {
   background-color: var(--dark); // overriding bootstrap styles here 
}

I am trying to apply it at the root of my application like this:

componentWillReceiveProps() {
        if (this.props.profile && this.props.profile.theme === 'dark') {
            require('./styles/dark.css');
        }
    }

It works great when running the application locally with yarn start . But when I actually build the app using webpack, it works really strange. Part of the new styles are applied and part on, regardless of which theme is selected. For example background is applied from the main theme and ignored in the dark theme but text color is the opposite.

Why is this happening?

It seems that the dark stylesheet is not being applied at all when building the app with webpack, although everything looks correctly when running it with yarn start .

I guess that you have a naming clashes, which overrides your css.

React supports CSS Modules alongside regular stylesheets using the [name].module.css file naming convention.

CSS Modules let you use the same CSS class name in different files without worrying about naming clashes

I solved my issues simply by importing all styled css sheets and then prefixing them like this:

.dark .card {
   color: black;
}

.light .card {
   color: white;
}

I assign class to the wrapper based on my props:

<div id="root" className={theme}>
   // content
</div>

Works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM