React. Why css classes from one FC work in other components without importing?

Viewed 77

I have a component. For this component I created css file with the description for the class "active" and imported it into the component. Also in this component I use NavLink from React Router. And NavLink gives for an element class "active", when user tapped this element.

In other component, which is fully separate, I also use NavLink. And there I didn't import css file with "active" class description. But all styles from the class "active" from the first component works also here. It means elements in this component don't look like they should.

Why it works so? And how I can make css file separate for each component?

Thank You.

2 Answers

Because you gave them the same name, if you'll read how "Bundling Assets" work what it does it compiles everything in the project and everything that got the same classes name will work everywhere.

I've noticed it when I had two different files of CSS for two different components but for the reason I wrote it took the CSS design from the other file. Then I changed the name of the class to something else and it worked.

Because react is put all css files in one file, and when that happen the classes with the same name override themselves. Read about "bundling assets and how it works". There is two method i know to avoid this issue :

1. don't write the same class names :
We suppose that you have two js files, "about" and "home", write the css classes in this way : .about-paragraph{...}, .home-paragraph{...} ....

2. Use Module: create the css file and name it about.module.css, and put the classes like you want. In js file import it like that :

import styles from "./about.css";

And use it with jsx like that :

<div className = {styles.paragraph}>
...
</div>
Related