CSS Modules in React TypeScript using Nx

Ye Min Ko
Learn React
Published in
2 min readJul 25, 2023
Photo by Timo Volz on Unsplash

Prerequisites

  • Make sure you have installed Node.js version 16+.
  • To follow along with this article, you’ll need a react project that is generated with Nx. If you haven’t done it yet, see this article.

You can still follow the article by creating components in your own way.

What is CSS Modules?

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. (see more)

Naming Convention

  • CSS Modules files must be written in this format.
[filename].module.scss

Use appropriate file extension based on your stylesheet choice. For example, app.module.css, app.module.sass or app.module.scss

  • CSS class names should be written in camelCase. But not mandatory.
.className {} // recommended

(or)

.class-name {}

Let’s Start

Open app.module.scss and write the following code.

App Component’s CSS file

And then, open app.tsx and write the following code.

App Component

There are two syntaxes to use CSS Module classes. You can use whatever you like but dot notation looks cleaner.

styles.container // recommended

(or)

styles['container']

Using Multiple CSS Modules classes

If you want to use multiple classes, you can use Template literals. For example, change the App component into this.

App Component

And put this code into app.module.scss file.

App Component’s CSS file

Serve the Application

Run with nx serve and see the result.

Done

CSS Modules can reduce potential conflict between css classes. That’s why if your not using yet, give it a try.

--

--

Ye Min Ko
Learn React

🌐 Web Developer | 👀 Self-Learner | 👨‍💻 An Introvert