Some Context
Usually class names for CSS are named like this class-name
, with a dash in between, it's called "kebab-case", like "CamelCase", is a cenvention to name variables.
Gatsby is based on react, and if use a CSS module like this:
- have a file named as
*.module.css
(or .scss, with plugins), such asheader.module.css
:
// header.module.css
.nav {
background-color: red;
}
- Then it can be used in the other files, for this case, maybe in
header.js
:
// header.js
import styles from "./header.module.css"
...
<div className={styles.nav}>
Hi
</div>
The benefits of using a CSS module is that the name class or ID will be compiled to a unique one. To be more specific, in the generated HTML, instead of <div class="nav">
it becomes something like <div class="header-module--nav--3ND4a"
. If you are defining another ".nav" in your body CSS module, you don't need to deal with naming conflicts.
OK, so far, so good.
However...
I tried to follow the CSS naming conventions - to "kebab-case" in my components. It didn't work.
For example, to use .nav-bar
class. The first thing to note is that instead of using className={styles.nav-bar}
, you need to use className={styles["nav-bar"]}
. Because the content inside brackets are interpreted in javascript's way and javascript doesn't recognize "-", or it thinks it's a "minus".
Even if you use dictionary access, it won't work. I did a bit research in Gatsby website. Gatsby has this link, looks like it is moved away from using it. As a novice, I don't really get why LOL.
But If You Really Want To
Here is a related thread.
What did I do? I just followed Gatsby's suggestions, sometimes I don't feel there is a need to argue. If the framework wants us to follow, I will follow, to make it work is more important to me. However, I do think it worth a note here so that if you need help, you either can take advantage of above solution, or can stop trying and save some time!