Why you should use CSS Modules in React

Use the CSS Modules in React

CSS Modules Stylesheet is one of React's best features, and I will tell you why you should take advantage of it. As a fan of TailwindCSS, there are times when you may not have a choice to work with your favorite tool. I enjoy CSS, but naming classes or ids holds me back.

Your class names may look something like the below:


// components/Car.tsx
export default function Car() {
  return (
    <div className="container">
      <h1 className="container__title">Cars Available</h1>
      {data.map((car: CarProps) => (
        <div className="car__container" key={car.id}>
          <span className="car__container__make">Make: {car.carMake}</span>
          <span className="car__container__model">Model: {car.carModel}</span>
          <span className="car__container__color">Color: {car.carColor}</span>
          <span className="car__container__year">Year: {car.carYear}</span>
        </div>
      ))}
    </div>
  );
}

I do not think it is terrible, I think this gives me enough information to target the correct elements when styling your CSS, but this can get quite difficult to maintain when your file grows.

What if your other files have the class name container like on this file? You will run into styling issues and have to think about creative ways to name the container so that another file does not overwrite them.

Guess what? You CAN use the container every single time without affecting other files!

Name your CSS file as such: [file_name].module.css

And now your class names can look like this:

// components/Car.tsx
export default function Car() {
  return (
    <div>
      <h1 className={styles.title}>Cars Available</h1>
      {data.map((car: CarProps) => (
        <div className={styles.container} key={car.id}>
          <span className={styles.make}>Make: {car.carMake}</span>
          <span className={styles.model}>Model: {car.carModel}</span>
          <span className={styles.color}>Color: {car.carColor}</span>
          <span className={styles.year}>Year: {car.carYear}</span>
        </div>
      ))}
    </div>
  );
}

Again, adding a container class in your App.tsx will not affect the Car component!

Another thing to note is when you inspect the element, it still gives the classes an identifier so that it would look something like this:

<span class="_make_dfnjw_1">Honda</span>

As you can see, the make class has a unique identifier. More information here

Codesandbox of the final product along with the CSS styling here