Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS module declaration doesn't work if I reference it on a specific body class

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.

like image 297
JackH Avatar asked Mar 03 '23 23:03

JackH


1 Answers

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.

like image 64
JackH Avatar answered Apr 06 '23 00:04

JackH