Using CSS modules in React

Using CSS modules in React

When it comes to building a website, CSS is an essential language that controls the presentation and styling of your webpage. However, it can be challenging to come up with unique names for each CSS element, especially if you're working on a large project.

One solution to this problem is to use CSS modules. CSS modules allow you to import your CSS file as an object, making it easier to target specific classes without worrying about naming collisions

Now, when you import your CSS files into your JavaScript code, you can assign them specific names:

To use a specific class from one of these files, simply add the import name to the class name, like this:

The file naming convention:

No alt text provided for this image


The import method inside the component:

No alt text provided for this image


Let's say you have a CSS class in ./activePositions.module.css named ".body", this is how you would target the class in your react component:

No alt text provided for this image


Instead of worrying about naming conflicts, you can define both CSS files as modules. This means that the scope of each CSS file will not affect outside components, even if the modules have the same name, it will only read inside that specific component.

Don't forget to add the keyword "module" to the end of each file name, like this: Example: "home.module.css"

CSS modules are a useful tool for managing CSS files, particularly on larger projects where naming conflicts can be problematic. By defining CSS files as modules, you can re-use class names without worrying about scope affecting components that need to be styled differently. This helps to improve the overall organization of your project and makes it easier to manage your CSS code.


This really helped me on my latest project, so I wanted to share it with the world!


Elias Grey

Software Developer

www.eliasgrey.me


#CSS #CSSmodules #webdevelopment #webdesign #coding #programming #classnames #organization #JavaScript #React #frontend

To view or add a comment, sign in

More articles by Elias Grey

Others also viewed

Explore content categories