Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules.

For example, if we have a component using regular css:

import React from 'react'
import "./styles.css";

const About = () => {
    return (
      <div>
        <h1 class="title">CSS Modules</h1>
          <span class="select2-selection select2-selection--single dropdown-container" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-static-cooldown-container">
          <span class="select2-selection__rendered" id="select2-static-cooldown-container" role="textbox" aria-readonly="true" title="1 hour">
            <span>
              <div class="icon icon-time-2"></div> 1 hour
            </span>
          </span>
          </span>

      </div>
    );
};

export default Dashboard;

But when working with css modules, the class names require modification:

import React from 'react'
import styles from "./styles.module.css";

const About = () => {
    return (
      <div>
        <h1 class={styles.title}>CSS Modules</h1>
          <span class="select2-selection select2-selection--single dropdown-container" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-static-cooldown-container">
          <span class="select2-selection__rendered" id="select2-static-cooldown-container" role="textbox" aria-readonly="true" title="1 hour">
            <span>
              <div class="icon icon-time-2"></div> 1 hour
            </span>
          </span>
          </span>

      </div>
    );
};

export default Dashboard;

Why is this necessary?

Aside from changing class names, what about other css elements or attributes like id? Moreover, what about components with multiple classes in their name? Do all those need modifications too?

Is there a way to utilize css modules without having to alter class names?

Although I haven't found a definite answer yet, it seems most people continue modifying class names despite the mess. However, part of me believes there must be a more efficient solution because this process is rather cumbersome

Answer №1

To discover similar code examples, try the following:

const Example = () => {
    const {name} = data;

    return (
      <div>
        <h1 className={name}>Sample</h1>
      </div>
    );
};

Replace "" with {} to make it work.

Answer №2

Another way to combine multiple classes in React is by using the Array.join method.

const About = () => {
    const {header, additionalClass} = styles;

// const mainClass = [header,additionalClass].join(' ');

      return (
      <div>
        <h1 className={[header,additionalClass].join(' ')}>Styling with CSS Modules</h1>
      </div>
    );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...

Error: Knockout sortable array failing to render nested elements accurately

As a newcomer to Knockout.js, I have recently delved into the world of JQuery and the knockout-sortable project. My current project involves utilizing a complex data structure to present forms. Specifically, I am attempting to create a nested sortable arra ...

Experiencing multiple errors with Npm audit problem, persistently occurring

Having a persistent issue in my new GitHub repository. I've cleared the cache, reinstalled npm multiple times, but nothing seems to resolve it. What steps should I take to fix this problem? Even after running npm audit fix, the same code keeps appear ...

Creating unique validation rules using VeeValidate 3 and vue.js

I have a form where I need to establish specific rules. For instance, consider the following code snippet: <label class="form-label">Price range from</label> <validation-provider rules="required_if:price_to" name="Price range from" ...

Stopping the execution of code in Node.js after returning a JSON response

When a user is not found, the code still continues executing after sending the JSON response. The JSON response is generated in a separate class and returned from there. var user = new UserClass(obj, null); var userObj = user.getUser(res, req, 'user ...

Guide on switching routes following an ajax call within redux

What is the best approach for handling ajax requests in a React application? In my scenario, I have a HomeComponent with links to other components. When a user clicks on one of these links, an ajax request needs to be made to fetch the initial state for t ...

Is the accuracy of Chrome's inspect device not up to par?

I'm currently testing how the page appears on a 1366x768 laptop. When inspected in the device, it looks perfect: However, on the actual laptop screen, it's completely off: It's so frustrating because I mainly work on a large screen and ca ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

Library that supports Base64 encoding and decoding for both C and JavaScript environments

Are there any base 64 encoding and decoding libraries that are compatible with both C and JavaScript? Ideally, the library would have identical algorithms for both the encode and decode functions, allowing it to be used for desktop application clients (C++ ...

"Troubangular: Troubleshooting unexpected behavior when trying to update ngFor after setting a property

Dealing with what seems like a straightforward component here. I'm fetching an array of objects from an API, storing them in a property, and then displaying them in a select list for the user to choose from. When the value changes, I filter the result ...

utilize the flex index.html layout

Upon reviewing the template, I noticed that there is code implemented to check if the client has the necessary version. This code performs certain actions based on whether or not the required version is available. Additionally, there seems to be an <obj ...

Python Flask server struggling to find JavaScript and CSS files within index.html when paired with AngularJS frontend

I'm currently working on a simple website project that involves a Python backend running on Flask and an AngularJS frontend. The main issue I am facing is encountering 404 errors when the index template tries to load CSS and JS files. Here's how ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Tips for preventing a promise from being executed more than once within an observable while being subscribed to a BehaviorSubject

I've defined a class called Store with the following structure: import { BehaviorSubject, Observable } from 'rxjs' export abstract class Store<T> { private state: BehaviorSubject<T> = new BehaviorSubject((undefined as unknown ...

How to add and append values to an array in a Realtime Database

My React.js app allows users to upload songs to Firebase and view the queue of uploaded songs in order. The queue can be sorted using a drag-and-drop system that updates the database in Firebase. Is there a way to insert these songs into an array when uplo ...

The onInvoke hook in Zone.js is receiving an inaccurate currentZone value

Greetings. In the comments for the ZoneSpec interface (found in zone.ts file), it states that the onInvoke hook must receive currentZone as the second parameter. If creating an interceptor zone, the reference to that zone should be passed as the second pa ...

Tips for transferring a value from a function in ASPX to a CS file

I seem to be overlooking a small detail. I have a dropdown list (DDL) and a function in my C# file. I want to pass the 'value attribute' of a selected DDL option to my function, but I can't seem to retrieve the value attribute. I checked the ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...