Clank Clank - 4 months ago 10
React JSX Question

ReactJS and classNames

I'm very new to ReactJS and currently using the MERN stack to create a new application.
I know, that I can use external stylesheets, by importing them:

import styles from ./Header.css


Usage:

<div className={styles["logo-home"]}>
test
</div>


.css file:

.logo-home {
background-color: #eee;
}


This is working fine, but I just can't find out, how to access something like:

.logo-home .inner {
background-color: #000;
}


I thought, this would work, when I write something like
styles["logo-home"].inner
or
styles.inner
, but it did not...

Whats the right / best way to solve this problem?

Answer

If you're cloning the MERN starter repo, you probably are using CSS modules (through webpack's setup).

The idea here is that you have your styles in a modular way with their own scope. This is achieved by adding some hashing to each classname. Like in this example:

Look at classnames

So assuming you have

<div className={styles["logo-home"]}>
   <div className={styles["inner"]}>
      bla bla bla
   </div>
</div>

Your imported .css file can look like this:

.logo-home { /* ... */ }
.inner { /* ... */ }

As you see, there is no need for CSS selectors as you would use in traditional CSS. You just map each container with one class name and CSSModules will make sure your class names don't collide among all your modules.

You can read more about CSSModules here