DEV Community

Brian Irons
Brian Irons

Posted on

React and Css

Hi all, I'm struggling to understand something. A style sheet for one component on my react project seems to be effecting the styles in another. I thought this was not suppose to happen with localised style sheets and components. Can anyone educate me?

Top comments (4)

Collapse
 
moopet profile image
Ben Sinclair • Edited

If the stylesheet has general selectors like p then they'll affect all paragraph tags. This is why every React component has classes for pretty much everything, and a big reason why the HTML looks so cluttered.

These sort of selectors will have global effects when the stylesheet is loaded with all the others:

p {}
p.foo {}
.bar {}
Enter fullscreen mode Exit fullscreen mode

The exception is if you load the stylesheet as a module:

// ...
import * as styles from './styles.module.scss';

// ...

return (
  <p className={styles.bar}>
    Hello there!
  </p>
);
Enter fullscreen mode Exit fullscreen mode

This takes care of the random class names for you, producing something like this:

<p class="styles_foo_9348nksdjfhsgogogoh">Hello there!</p>
Enter fullscreen mode Exit fullscreen mode

which is guaranteed by the build system not to conflict with any other style. Everything in a style module should be a class definition, and it'll all happen by magic.

Collapse
 
link2twenty profile image
Andrew Bone

Here's the official documentation.

Adding a CSS Modules Stylesheet

Collapse
 
brense profile image
Rense Bakker

Make your life less complicated and use a CSS in JS library like emotion or styled components... Or even better, use a UI framework like @mui that has CSS in JS built in 😬

Collapse
 
wjplatformer profile image
Wj • Edited

Halo, halo. Your regular asian guy is here to help you. But first, I require a screenshot. Yes, you need to send screenshot of code and site if not it is not clear 🥺