Clank Clank - 1 year ago 76
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


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

.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
, but it did not...

Whats the right / best way to solve this problem?

Answer Source

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

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