DEV Community

loading...

Less annoying CSS in React with CSS modules

fawazsullia
A javascript developer with a passion for building. Fullstack, because it lets me convert ideas into reality. Sharing my learnings.
・1 min read

A fundamental problem with CSS is that it's globally scoped.

So, if you have a number of components in your React app, you would have to think of unique classes to name your components.

And the bigger your app gets, the harder.

This is where CSS modules come in.

CSS modules let you create CSS files that are locally scoped.

Here's how you do it;

  1. Create a CSS file with .module.css extension
  2. In your component, use import * as anyName from 'relative path'
  3. And in yout jsx elements, use className={anyName.nameofclass}
  4. In your module.css file, use .nameofclass to select the elements

Note that, you can select child elements with .nameofclass element name as well (.container button)

This way, you don't have to worry about thinking of unique names to name your class.

Note: Css modules are not intrinsic css features. On compilation, they get compiled to normal css. You would need the right compiler configuration to be able to use this. If you use web pack, it's already included.

If you found this useful, let me know in the comments. if there's a better way to CSS in react, drop a comment

Discussion (8)

Collapse
pcjmfranken profile image
Peter Franken

FYI This does not just work out of the box, it requires a compiler with the right configuration. Perhaps you could add some setup instructions to the post, or at least mention this prerequisite.

Other than that, yeah, CSS Modules are awesome! Very performant, easy to work with, and with the right compiler config you could even use SASS.

Collapse
fawazsullia profile image
fawazsullia Author

Thanks for the suggestions man. I'll add it there.

Collapse
fawazsullia profile image
fawazsullia Author

I guess the compiler is included in webpack

Thread Thread
pcjmfranken profile image
Peter Franken

Yes through css-loader likely. What platform (e.g. Create React App / Next.js / Nuxt / etc.) would you usually use as a base if you don't mind me asking?

Thread Thread
fawazsullia profile image
fawazsullia Author

Create react app mostly. Sometimes Gatsby.

Collapse
oenonono profile image
Junk

FYI, CSS is no longer globally scoped. You can create isolated CSS scopes in the DOM. This has been true for years now. Please stop spreading misinformation.

Collapse
fawazsullia profile image
fawazsullia Author

Thanks for letting me know. Can you reference something pointing to it? because i couldnt find much.
Also, would appreciate if your tone was a bit friendly

Collapse
oenonono profile image
Junk • Edited

Try looking up "Shadow DOM." MDN and Google Web Dev docs will be good sources. I believe CSS Tricks also has some good articles.