Andre Tran
Andre Tran

Reputation: 67

React js css stylesheet applied to more than one component

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

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?

Upvotes: 2

Views: 1014

Answers (2)

Solomon Bush
Solomon Bush

Reputation: 165

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.

Upvotes: 0

Yousaf
Yousaf

Reputation: 29282

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.

Upvotes: 2

Related Questions