Page Content

Tutorials

What Are The CSS Modules In React.js

CSS Modules

CSS Modules
CSS Modules

By localising class names, CSS Modules offer a potent method for developing component-specific styles in React programming that successfully guards against style conflicts. This approach offers a comprehensive way to address frequent stylistic issues that arise in contemporary online applications, especially as projects get bigger and more complicated.

In this phase, you used CSS stylesheets that were imported straight into a component to style it. Using standard CSS files to style React elements is a fast method of creating components with related styles. When working on new or small projects, its ease of use makes it a good starting step; nevertheless, as the project grows, it may become problematic.

Class name conflicts and unintentional style application are two common stylistic issues that you ran into when building the components. Standard CSS can be used to get around them, but other styling strategies provide you with the means to deal with these issues programmatically rather than through naming conventions. You will investigate using style objects to solve these issues in the following phase.

The Problem: Global CSS Scope and Conflicts

Since CSS styles have a global reach, any style rule can affect any site element. This global nature causes huge challenges in larger systems, especially when multiple developers are working on various components or when reusing components across different regions of an application or even unrelated projects, but it is easy for small, simple projects.

The global CSS scope gives rise to two main issues:

Class Name Conflicts: It is more likely that different developers would unintentionally use the same class name for various purposes as a project grows in size. Applying these same class names can cause them to override one another’s styles, which can result in unexpected visual hiccups and challenging debugging problems. Though they try to reduce conflicts, traditional remedies such using verbose naming conventions like BEM (Block, Element, Modifier) can become complicated and yet not completely solve the issue in very big codebases.

Unintended Style Application (Cascading Issues): CSS cascading can “leak” styles from parent components to deeply nested child components, even if they weren’t meant to, in addition to name conflicts. This can lead to unexpected child component styling, affecting user interface consistency.

React apps, which promote component sharing and bundling, make these issues worse because components may be created separately and then incorporated into other contexts, raising the possibility of style conflicts.

How CSS Modules Provide a Solution

By offering a way to scope CSS class names locally to certain components, CSS Modules resolve these problems and get rid of global conflicts.

The fundamental mechanism consists of:

File Naming Convention: CSS Module stylesheets are distinguished by a particular naming convention, which usually ends in.module.css (ExpenseEntryItem.module.css, for example). This standard tells the React toolchain which includes webpack, which is frequently used in the background that these files ought to be handled as CSS Modules.

Importing Styles: CSS Modules are imported as JavaScript objects into a React component, as opposed to being linked globally or imported directly as a side effect. Import styles from ‘./ExpenseEntryItem.module.css’, for instance.

Referencing Styles: The styles are then referred as attributes of the imported styles object within the JSX of the React component, such as className={styles.itemStyle}.

Localized Class Names: The CSS Module transformation renames the class names in a unique way during the development process (for example,.itemStyle may become ExpenseEntryItem itemStyle xyz789). This approach guarantees global uniqueness even if the class name was used in other CSS Modules. This prevents class name conflicts in ComponentA.module.css and ComponentB.module.css. CSS Modules avoid name conflicts and ensure styling without overrides or leaks by localising all styles.

Benefits and Advantages of Using CSS Modules

CSS Modules improve the development process and maintainability of React apps in a number of important ways.

Protection Against Style Conflicts: The main benefit is protection against style conflicts. CSS Modules’ localisation of class names prevents styles from influencing each other even if two components have the same class names. Complicated naming conventions like BEM are not necessary with this automated solution.

Component-Specific Styling: Styles and their corresponding components are closely related. Because their styling is certain to follow them wherever they are used, components become genuinely self-contained and reusable, encouraging uniformity throughout the application.

Modularity and Maintainability: CSS files grouped with their components (e.g., Component.js and Component.module.css) improve project modularity and maintainability. It helps developers understand which styles go with which components and update or delete styles without affecting other application components.

Familiar CSS Syntax: Standard syntax is a well-known and tried-and-true approach that developers can continue to use when writing CSS. Learning complex JavaScript-in-CSS patterns or a new styling language is not necessary unless you want to.

Clarity and Readability: The relationship between the component and its styles is made extremely evident within the JavaScript code by the explicit import and direct referencing of styles (e.g., styles.itemStyle).

Bundler Integration: Webpack and other module bundlers, which manage the optimisation and transformation of CSS at build time, including dividing it into smaller pieces if required, integrate effortlessly with CSS modules.

Code Example:

import React from 'react';
import './ExpenseEntryItem.css'; 
import styles from './ExpenseEntryItem.module.css'; 
class ExpenseEntryItem extends React.Component {
   
    constructor(props) {
        super(props);
    }
    render() {
        return (
            // **Applying the locally scoped style using the 'styles' object**
            <div className={styles.itemStyle}>
                <div><b>Item:</b> <em>Mango Juice</em></div>
                <div><b>Amount:</b> <em>30.00</em></div>
                <div><b>Spend Date:</b> <em>2020-10-10</em></div>
                <div><b>Category:</b> <em>Food</em></div>
            </div>
        );
    }
}
export default ExpenseEntryItem;

In this example:

  • In order to define React components, the React library must be imported using the line import React from’react’;. ExpenseEntryItem.css’ is imported; if the component additionally makes use of a conventional, global CSS file, this line may appear. This illustrates how CSS Modules and other styling techniques can coexist. The next import is crucial for localised styling.
  • import ‘./ExpenseEntryItem.module.css’ styles; the crucial line for CSS Modules is this one. It imports the ExpenseEntryItem.module.css file as a JavaScript object called styles rather than a direct CSS import. The CSS file’s modified, locally scoped class names will be included in this styles object.
  • React is extended by the class ExpenseEntryItem.Component {… }: A React class component is defined here. The JSX describing the component’s user interface is returned by the render() method.
  • The CSS Module is used in this section we utilise a JavaScript expression styles.itemStyle in place of the standard string className=”itemStyle”.

Usually, you would use a command like npm start to run this example (assuming a Create React App setup). The ExpenseEntryItem component with the brown text and 14px font size would appear when you opened your browser after running the application. If you used the browser developer tools to examine the element, you would see that the div element had a generated, unique class name applied to it, indicating that CSS Modules were in use.

Conclusion

By enabling developers to create styles using well-known CSS syntax and offering a strong, integrated system for localising class names and avoiding style conflicts, CSS Modules achieve a useful balance.They work well for scalable React projects with predictable and stable styles. Project size, team preferences, and individual needs determine design. There is no “one-size-fits-all” React solution. For style interference protection and explicit component encapsulation, CSS Modules are simple and effective.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index