July 10, 2020

How to use css Modules in react?

CSS modules is a term in which CSS are scoped locally. If we import CSS file in a particular javascript file then classes in the imported CSS file is accessible inside that javascript file only.

CSS Module is not a feature which directly available on the browser it takes place at the compilation phase

Topics we will cover in this article that how CSS modules will work for different scenario

  • Single class Name
  • Multiple class name on the same element
  • Nested class Names
  • Composition
  • How CSS work for tag name and id selectors
  • Media queries
  • Conclusion

and we will use CSS modules with react examples

As I said CSS Modules are not directly available in the browser it is managed at compilation phase, so we need to some configuration in a bundler to enable CSS modules functionality

For eg., If you are using webpack for bundling then we need to configure like below

{
	loader: "css-loader",
	options: {
	    modules: {
	        localIdentName: "[name]__[local]___[hash:base64:5]",
	    }		
	}
}

The above code enables the CSS module name functionality.

Before going into deep we should know how it works.

Please subscribe for web development tutorials

How did CSS Modules work?

Consider if you want to apply CSS for a particular section of an application then what we will do.

for eg. You want to add red font color to a particular section of an application then what you will do, there are some possible scenario which is as below

  • Giving a unique class name which is not been used anywhere
  • Applying CSS with a nested class
  • Apply CSS with sibling class

There are some other ways to do it but this is possible and will not go any conflict with another class name if it is small application, But for the big application you can’t guarantee that CSS class name will not duplicate so it’s very hard to maintain

So, here CSS modules come to the rescue. By enabling CSS modules feature CSS will be so-called locally scoped it means when we import CSS into the javascript file then it creates a unique name for each and every class name like below

Visual design for how css module works is as below

Above is a diagrammatical explanation for CSS modules now let’s check actual example

.red {
    color: red;
}

After compilation

.Style__red___1dIEw {
    color: red;
}

This is the compiled CSS which will be shown on the browser

Now I know what your’s next question if class red CSS replaced with some unique name then how to write code and add CSS to the elements

So here is an answer

You don’t need to take care of this because CSS modules give provision to use a red class on the element directly without worrying about what happened with CSS class name.

Actually, after compilation CSS modules have another output which is usually hidden from you it means it creates a javascript object which has original class name reference with the generated class name

like below

{
  red: .Style__red___1dIEw
}

So, the above code is a javascript object, So in below way, we can use it in our application

Here is full-example

//style.css

.red {
    color: red;
}
//example.js
import React, { Component } from 'react';
import style from './Style.css'
export default class CssModulesExamples extends Component {
 render() {
     return (
         //single class name
         <section className={style.red}>
            Single class Name example
         </section>
       
     )
 }
}

Note: we are demonstrating with react js example

as you can see we have imported style.css in example.js file and we are using style.red instead of writing generated a unique class names.

CSS modules are more useful when we are writing css in javascript file which is not valid for most of the cases, Its very useful in react application because there we write in JSX file which is nothing but javascript version of HTML.

Now take a look at the different scenarios of CSS modules. As of now, we saw how to deal with the single class name there might be the case you need to deal with the nested class name, sibling class name, etc.

Nested class Names

In nested class Name, There is a parent class and child class. with the combination of parent and child class, CSS gets applied, Let’s see how CSS modules deal with it.

For eg.

//style.css

.parent .bold{
    color: blue;
    font-weight: bold;
}
//generated compiled css

.Style__parent___w-O8Y .Style__bold___1vZ-u {
    color: blue;
    font-weight: bold;
}

//example.js
<section className={style.parent}>
                <p className={style.bold}>
                    Nested Class Name Example
                </p>
</section> 

I think the above code is clear enough to understand, how nested class works we have taken style.parent as parent and style.bold as child

Multiple classes on same element

Multiple classes on the same element. It means we have some CSS classes which we need to apply on the same element and some CSS we need to apply with the combination of a sibling so it will get applied to that element only.

Let’s see how it would work with CSS modules

//style.css

.red.bold{
    font-style: italic;
}
//generated compiled css
.Style__red___1dIEw.Style__bold___1vZ-u {
    font-style: italic;
}
//example.js 
<section >
                <p className={`${style.red} ${style.bold}`}>
                    Multiple class Name Class Name Example
                </p>
 </section>  

In the above example, we can see class red and bold are sibling which got applied on the same element to apply CSS property font-style.

In the above example, we need to concatenate two classes, it looks like a little complicated to write code with concatenating. To overcome this complication and to make it handy, we can use Classnames package.

Composition

CSS modules allow you to inherit CSS from other class also

Let’s see how it is possible

.red {
    color: red;
}
.mainClass {
    composes: red;
    text-align: center;
}
//compiled css
.Style__mainClass___2jOHI {
    text-align: center;
}

<style>
.Style__red___1dIEw {
    color: red;
}

// generated HTML in the browser
<section>
<p class="Style__mainClass___2jOHI Style__red___1dIEw">Composition Example</p>
</section>
//Example.js
<section >
                <p className={style.mainClass}>
                    Composition Example
                </p>
</section> 

In above if you see class mainClass have access to class red also it means CSS color: red and text-align: center will be applied to the above paragraph

In CSS modules composition, It is also possible to integrate CSS class from different file

Let’ see how it is possible.

//main.css
.commonClass {
    font-family: Arial, Helvetica, sans-serif;
}
//style.css
.compositeClass {
    composes: commonClass from './Main.css';
    font-weight: bold;
    color: red;
}
//Example.js  
<section >
                <p className={style.compositeClass}>
                    Composition Example with two different files
                </p>
  </section> 

In the above example, you can see we have combined commonClass in compositeClass where commonClass is in other file

Media queries

If you are using Media queries, No need to do extra work

for eg.

//style.css

.small {
    font-size: 40px;;
  }
  .large {
   font-size: 50px;
  }
  
  @media (max-width: 600px) {
    .small {
        font-size: 20px;
    }
    .large {
        font-size: 30px;
    }
}
//generated compiled css

.Style__small___NfhsW {
    font-size: 20px;
}

.Style__large___2yU03 {
    font-size: 30px;
}

@media (max-width: 600px)

.Style__small___NfhsW {
    font-size: 20px;
}

.Style__large___2yU03 {
    font-size: 30px;
}

}

//Example.js 
<section >
                <p className={style.small}>Media query example 1</p>
                <p className={style.large}>Media query example 2</p>
 </section> 

In the above example, if you see CSS modules take care of media queries also we don’t need to do extra work for it.

How does CSS Module work for the tag name and id selectors?

Until now we have dealt with className only but what about id and tag selector

For id selector, it also works the same as class name but as per CSS standard we should have unique id per element it should not be reuse but in the big application, we can guarantee that so CSS modules take care of it also.

For tag name CSS does nothing it renders as it is no unique id generates for it.

Conclusion

Regardless of whether or not CSS Modules will be helpful to you – now you know. If you do decide to use CSS Modules, there should be no surprises

Leave a Reply

Your email address will not be published. Required fields are marked *