2

I have a Parent.js component with a child component Child.js inside of it.

  • Parent.js imports parents.css

  • Child.js imports child.css

If I define this in child.css:

.example {
  font-family: 'Roboto', sans-serif;
}

How come I'm able to use this className in the Parent.js component as well despite not specifying it in the parent.css?

Andre Tran
  • 57
  • 1
  • 7
  • 1
    Does this answer your question? [How to make React CSS import component-scoped?](https://stackoverflow.com/questions/47090574/how-to-make-react-css-import-component-scoped) – Mosh Feu Jul 01 '20 at 06:01
  • You can use CSS-in-JS or CSS modules for the specifying styles separately. This might help: https://medium.com/@pioul/modular-css-with-react-61638ae9ea3e – Darsh Shah Jul 01 '20 at 06:05

2 Answers2

2

Unless you use unique class names, CSS Modules or some other alternatives available for scoping CSS styles to any component in React, styles specified in any CSS file will be applied globally.

If you want to limit styles to any component, use CSS Modules or make sure every class name is unique in your project.

For details on how to use CSS Modules, see Adding a CSS Modules Stylesheet. You can also look at 9 Ways To Implement CSS in React JS for other available alternatives.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

I recommend using unique class names. For example, lets say you have multiple ListView components: MemberUsersListView, AdminUsersListView, TestUsersListView; and each of them needs to be styled differently. I would create the following CSS classes:

.MUListView{
  ...
}
.AUListView{
  ...
}
.TUListView{
  ...
}

I know this seem's annoying, but it's cleaner than applying inline styles and easier to implement on smaller projects.

Solomon Bush
  • 165
  • 9