Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Styling with the CSS Modules | Styling in React Apps
React Mastery
course content

Contenido del Curso

React Mastery

React Mastery

1. Introduction to React Fundamentals
2. Styling in React Apps
3. React Hooks and Context
4. React in the Real World

bookStyling with the CSS Modules

CSS modules is an approach that allows us to scope CSS class names to specific components locally. It provides a way to write CSS code modular and encapsulated, reducing the chances of style conflicts and making the styles more maintainable. In fact, it has become one of the most widely adopted approaches for organizing React projects.

File-folder organization

Suppose we have the following user interface composed of three components: VideoPlayer, AuthorInformation, and VideoDescription.

We won't consolidate all components and styles into a single file. Instead, we will establish a separate folder for each component. Within each folder, we will create a jsx file for rendering and logic purposes and a css file for applying styles. Each css file should have the module.css at the end to achieve modularity. Thus, the structure would appear as follows:

Note

This approach offers a convenient solution for creating React components and writing styles. It ensures that each component is isolated and can be reused effectively. Locally scoping class names enhances code organization, promotes reusability, and avoids style conflicts.

Syntax

Let's explore the syntax of using modular styles for a component, using the VideoDescription component as an example.

Inside the VideoDescription.jsx, we create a component that generates a specific markup. There's nothing particularly new or unfamiliar about it.

The difference arises when we want to apply a class name. First, we must import the VideoDescription.module.css file into the VideoDescription.jsx file. We can accomplish this using the following syntax:

  • <file_name> can be any word we associate with the file. Generally, the name is given like: css, styles, or simply s;
  • <file_path> is the correct path to the file. We already know the syntax: ./.

Result:

To assign a class name to the element, we can utilize the className attribute. Within this attribute, we enclose the desired class name within curly braces {}. Inside the braces, we include the specific word associated with the styles file, followed by a dot . and the class name. Result: className={css.text}. text is the real class name.

Now we can open the VideoDescription.module.css file and apply the styles to the the p element with the text class name using class selector:

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 8
some-alt