How to use Style Module in React JS

This blog going to be the shortest one, because this is an easy topic but very important.

So I decided to write a blog on this.

Basically when we create a react app and add CSS, it works perfectly on a local machine but on the server or after uploading the build on the server all the CSS gets compiled, and if there are the same CSS classes throughout the project then the design may be disturbed.

Because there may be different designs inside each component but by mistake, the class name of elements is the same.

So to avoid this issue we use Style Modules.

What Style Module Do ?

So style module makes sure that each element in each component get styled with a unique class and no design overlap occurs due to the same class name inside components.

Below you will see the code without the style module.

App.js File

import style from './App.css';

function App() {
  return (
    <div class="paddingClass">
      <div class="red">This is a Red color div</div>
      <button class="button" type="button">Change my color to blue</button>
    </div>
  );
}

export default App;

App.css File

.paddingClass{
  padding:10px;
}
.red{
  color:red;
  margin:10px;
}
.button{
  background:blue;
  color:white;
  border:0px;
  padding:5px;
  margin:10px;
}

So these two files App.js and App.css are using the basic techniques to add a style class to an HTML element. But as I told you during build these classes get overridden with other classes with the same name.

To avoid this problem we use the Style Module, First of all, we need to rename our App.css class to App.module.css, and then we just need to modify the App.js file rest code in the App.css file will remain the same in the App.module.css file.

Now App.module.css file will remain the same as App.css like the above code, But the App.js file code will change to the below code.

import style from './App.module.css';

function App() {
  return (
    <div class={style.paddingClass}>
      <div class={style.red}>This is a Red color div</div>
      <button class={style.button} type="button">Change my color to blue</button>
    </div>
  );
}

export default App;

In the above code, we are importing the App.module.css file with a reference variable name style, you can name it whatever you want, but should be valid according to javascript variables.

With this style variable, you can access all classes of the App.module.css file.

This Style Module generates unique classes for each component, Let’s see the output of the above code.

As you can see the Style Module generated classes are unique and will not overlap with other classes after project build.

That’s it for this blog if you like it please comment and share with your friends. 🙂

Related Posts

Leave a Reply

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

×