I am new to React and Gatsby.js. I am building a blog with Gatsby and my blog has a toggle to switch between light and dark modes. I am achieving this by toggling a class on the <body>
tag with JavaScript. Essentially, if it is light mode, the tag will be <body>
and if it is dark mode, the tag will be <body class="darkMode">
.
I have managed to get this to work just fine by using vanilla JavaScript to set and remove the .darkMode
class on the <body>
tag. However, I am having some trouble styling elements based on body.darkMode
in my CSS modules.
In my index.module.css file, I have the following classes:
.section {
color: #141414;
}
body.darkMode .section {
color: #ebebeb;
}
In my index.js component, I have imported the CSS module and applied the style like this:
<section className={indexStyles.section}></section>
While the color property in the .section
class does work, I notice that the body.darkMode .section
declaration does not work when I add the .darkMode
CSS class to the <body>
tag. Why is this? Help appreciated. Thanks.
I figured out the solution. It turns out, Gatsby was compiling the body.darkMode .section
into some arbitrary classnames. In reality, I wanted it to ignore body.darkMode
but reference the local generated class name for .section
.
I found the answer here - https://github.com/webpack-contrib/css-loader#scope. I was able to solve my specific issue by converting the original CSS to:
.section {
color: #141414;
}
body:global(.darkMode) :local(.section) {
color: #ebebeb;
}
As you can see, the :global and :local selectors allow you to target your HTML correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With