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

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

designing a responsive form in the mobile environment

I have implemented a search form on my website with a button inside the text box. It works fine on desktop, but when I switch to mobile view, the positioning is off. I am currently using absolute positioning for the button to give it a fixed position. Is t ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

What is the best way to use jQuery to select a group of table rows based on the value of a

My current issue involves using a jQuery selector to move table rows "UP" and "Down." Here is the Table structure in HTML: jQuery Portion : $(".up,.down").click(function() { var row = $(this).parents("tr:first"); if ($(this).is(".up")) { ...

navigate to a new page in vue with node.js

As I continue to expand my knowledge in JavaScript, Vue, and Node.js, I encountered a specific issue that I need help with. My goal is to redirect the Vue page after logging in using Node.js. Below you'll find the code snippets for my Vue setup and sc ...

Adjust the size of the container DIV based on the content within the child DIV

I have been searching for a solution to my question without success. Here is the issue: I have a DIV that acts as a container for a Post in my project. Inside this post are classes for the poster avatar, name, timestamp, text, and more. The problem arise ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...

The submission of the Ajax form isn't functioning as expected

I have created a feedback form with an image submit button instead of the regular HTML submit button. When I try to submit the form, the "data:" value always returns as NULL. Can you help me identify the issue in my code? Here is the code snippet: The FOR ...

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

Deciding Between Two Columns or One Column for Your JQuery Accordion

I am currently working on customizing an Accordion that is too large in height for my liking. My goal is to convert the single column layout into a two-column display, side by side. Having multiple items in one column results in excessive height, hence t ...

Having trouble showing the individual data retrieved from the API in React-JS

I'm having trouble showcasing the necessary information from an API response on the frontend. The API fetch code is as follows: async function obtainNFTData(){ const answer = await fetch(`https://api.rarible.org/v0.1/items/${chain}:${address}:${Id ...

Issue with React / Express failing to route links accurately

Currently, my React project is functioning well except for Express. I have been struggling to find comprehensive tutorials on implementing correct routing with Express in a MERN stack application. I have come across some Stack Overflow posts, but none of ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

The typescript error "Cannot read properties of undefined" is encountered while trying to access the 'map' function

I was attempting to follow a guide on creating an app using typescript and react, but I'm encountering an error that says "Cannot read properties of undefined (reading 'map')". I'm not sure why this is happening, can someone please offe ...

The controller's AngularJS function seems to be unresponsive

Issue with AngularJs ng-click Event I'm attempting to utilize the GitHub Search-API. When a user clicks the button, my Controller should trigger a search query on GitHub. Here is my code: HTML: <head> <script src="js/AngularJS/angula ...

Unable to use NodeJS await/async within an object

I'm currently developing a validation module using nodeJs and I'm facing difficulties understanding why the async/await feature is not functioning correctly in my current module. Within this module, I need to have multiple exports for validation ...

"Can you provide guidance on displaying a form for a specific element based on its unique ID

I am trying to display the edit form when clicking on a specific image, but it is currently showing for all tasks. I need help in figuring out how to make it show only for one task. I attempted to use useState to change the boolean value "active" to show ...