Issues with CSS modules in React version 16.6.0 causing functionality to fail

I recently attempted to implement CSS Modules in my React project.

Below is a snippet of code from my App.js file:

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

const App = () => {
    const REACT_VERSION = React.version;

  return (
    <div>
      Main app
      <div style={styles.test}>Green</div>
      <div>Yellow</div>
      <div>React version: {REACT_VERSION}</div>
    </div>
  );
};

export default App;

And here is the snippet of code from my index.css file:

.test {
  background: black;
  color: white;
  font-size: 34px;
  border: 34px;
}

This is how the output looks like:

https://i.sstatic.net/oA7DD.png

I understand that I need to make changes to

  • webpack.config.dev.js
  • webpack.config.prod.js

However, after reading this helpful article, I couldn't locate the specific code mentioned.

Answer №1

Facing a similar issue, I managed to resolve it by simply renaming my CSS file to:

myUniqueName.module.css

Furthermore, I imported the styles as follows:

import newStyles from './myUniqueName.module.css'

No need to go through the hassle of updating webpack files anymore.

Answer №2

With React 16.13 and above, there is no need to eject your project anymore. Ensure that your CSS files are named in camelCase + .modules.css format and import them into your projects like so:

import React, { Component } from 'react';
import styles from './app.module.css'; // Import css modules stylesheet as styles
class App extends Component {
  render() {
    return <button className={styles.test}>Error Button</button>;
  }
}
export default App;

In the app.module.css file:

.test{
  color: blue;
}

If you do decide to eject the project, make sure to update the css modules section in the webpack.config.js file like this:

   test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
                modules: true,

Answer №3

The individual in a previous question was correct, however, they made a small mistake. You can achieve the desired result without updating the configuration. Simply add .module before the name of your CSS file like this:

myName.module.css

Then use it like this:

import styles from './myName.module.css'

This solution is tested and works on React 16.6

Answer №4

By using the * as notation, my issue was resolved.

import * as navStyles from './navigation.module.scss'

Answer №5

This tweak will definitely be beneficial for you. Navigate to the config/webpack.config.js file and locate a block that looks like this.

        {
          test: cssRegex,
          exclude: cssModuleRegex,
          use: getStyleLoaders(
            {
              importLoaders: 1,
              sourceMap: isEnvProduction && shouldUseSourceMap,
            },
            'css-loader'
          ),
         sideEffects: true,
        },

Modify it as follows:

        {
          test: cssRegex,
          exclude: cssModuleRegex,
          use: getStyleLoaders({
            importLoaders: 1,
            sourceMap: isEnvProduction
                ? shouldUseSourceMap
                : isEnvDevelopment,
            modules: {
              getLocalIdent: getCSSModuleLocalIdent,
              localIdentName: '[name]__[local]__[hash:base64:5]'
            }

          }),
          sideEffects: true,
        },

Repeat the same process for the cssModuleRegex block right after the previous block, then restart your server to enable CSS modules.

Answer №6

I believe this solution will work for your needs.

  • After upgrading to react version 16.8.2, you may notice that the config/webpack.config.dev.js and config/webpack.config.prod.js files are no longer present in webpack after version 16.2.0.
  • Instead, post-ejection in a react app, you will only find the config/webpack.config.js and config/webpackDevServer.config.js files. To address this issue, navigate to the config/webpack.config.js file and implement the necessary modifications.(Refer to lines 391 to 464)

            {
          test: cssRegex,
          exclude: cssModuleRegex,
          use: getStyleLoaders({
            importLoaders: 1,
            sourceMap: isEnvProduction
              ? shouldUseSourceMap
              : isEnvDevelopment,
    
            modules: true,
            getLocalIdent: getCSSModuleLocalIdent,
            localIdentName: '[name]__[local]__[hash:base64:5]'
          }),
          // Don't consider CSS imports dead code even if the
          // containing package claims to have no side effects.
          // Remove this when webpack adds a warning or an error for this.
          // See https://github.com/webpack/webpack/issues/6571
          sideEffects: true,
        },
        // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
        // using the extension .module.css
        ...
    

Answer №7

Make sure to name your CSS files using the format "yourFileName.module.css". Then import them into your JS file as shown below: import yourVariableName from "./yourFileName.module.css";

This setup is tested and works well with the following React versions:

"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.0"

Answer №8

Verified on React 17.0.1

Here is the step-by-step solution:

  1. Change the name of your CSS file from 'index.css' to 'index.module.css'. The specific notation doesn't matter as long as it ends with *.module.css.

  2. Import your *.module.css into your JavaScript file:

    import style from './CourseGoalList.module.css';

  3. Refer to your CSS classes using the standard CSS Modules syntax:

    ... className={style.NameOfTheCssClass}...

  4. If you have classes with dashes, you can either rename them to UpperCase or camelCase, or access them like a Map object (key: value pairs).

For example, choose one of the following options:

Variant A: Works perfectly

JavaScript File:

import React from 'react';
import CourseGoalItem from '../CourseGoalItem/CourseGoalItem';
import style from './CourseGoalList.module.css';

const CourseGoalList = props => {
  return (
    <ul className={style.GoalList}>
      {props.items.map(goal => (
        <CourseGoalItem
          key={goal.id}
          id={goal.id}
          onDelete={props.onDeleteItem}
        >
          {goal.text}
        </CourseGoalItem>
      ))}
    </ul>
  );
};

export default CourseGoalList;

CSS File:

.GoalList {
  list-style: none;
  margin: 0;
  padding: 0;
}

OR:

Variant B: Works perfectly

JavaScript File:

import React from 'react';
import CourseGoalItem from '../CourseGoalItem/CourseGoalItem';
import style from './CourseGoalList.module.css';

const CourseGoalList = props => {
  return (
    <ul className={style['goal-list']}>
      {props.items.map(goal => (
        <CourseGoalItem
          key={goal.id}
          id={goal.id}
          onDelete={props.onDeleteItem}
        >
          {goal.text}
        </CourseGoalItem>
      ))}
    </ul>
  );
};

export default CourseGoalList;

CSS File:

.goal-list{
  list-style: none;
  margin: 0;
  padding: 0;
}

However, avoid this approach that won't work:

Variant C: Does not work (even if the CSS class is visible in your JS file in an IDE like WebStorm)

JavaScript File:

import React from 'react';
import CourseGoalItem from '../CourseGoalItem/CourseGoalItem';
import style from './CourseGoalList.module.css';

const CourseGoalList = props => {
  return (
    <ul className={style.goalList}>
      {props.items.map(goal => (
        <CourseGoalItem
          key={goal.id}
          id={goal.id}
          onDelete={props.onDeleteItem}
        >
          {goal.text}
        </CourseGoalItem>
      ))}
    </ul>
  );
};

export default CourseGoalList;

CSS File:

.goal-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

Answer №9

After encountering compatibility issues between the CSS module tutorial I was following and my version of React, I found a solution that worked for me. The tutorial used React 16.0.0 while I had 16.7.0 installed. Unlike the tutorial setup with separate development and production versions on webpack, I only had a webpack.config.js file. The key change I made was in the code snippet located around line 400:

{
     test: cssRegex,  
     exclude: cssModuleRegex,
     use: getStyleLoaders({
          importLoaders: 1,
          sourceMap: isEnvProduction && shouldUseSourceMap,

          //this is where the modification took place.
         //================================================
          modules: true,
          getLocalIdent: getCSSModuleLocalIdent,
          localIdentName: '[name]__[local]__[hash:base64:5]'
          //================================================


     }),
     sideEffects: true,
},

This adjustment resolved the issue for me. Hope this information proves helpful to others.

Note: all content mentioned here is what I specifically added, everything else remained unchanged.

Answer №10

When working with CSS classes or IDs in your code, you don't necessarily need to define them as variables and import CSS separately.

 import React from 'react';
 import './index.css'

    const App = () => {
        const REACT_VERSION = React.version;

      return (
        <div >
          Main app
          <div className="test">Green</div>
          <div>Yellow</div>
          <div>React version: {REACT_VERSION}</div>
        </div>
      );
    };

    export default App;

Alternatively,

import React from 'react';
const style ={
  background: black,
  color: white,
  fontSize: 34px,
  border: 34px
}

    const App = () => {
        const REACT_VERSION = React.version;

      return (
        <div >
          Main app
          <div style={style}>Green</div>
          <div>Yellow</div>
          <div>React version: {REACT_VERSION}</div>
        </div>
      );
    };

Answer №11

  1. To begin the project, follow these steps:

    create-react-app projectname --scripts-version 1.1.5
    
  2. Next, run:

    npm run eject
    
  3. Don't forget to add CSS-loader to both webpack.config.prod.js and webpack.config.dev.js files. It's important to include specific settings for optimal functionality with react CSS modules.

    {
       loader: require.resolve('css-loader'),
           options: {
              importLoaders: 1,
              modules: true,
              localIdentName:'[name]__[local]__[hash:base64:5]'
    }
    

Answer №12

To activate the css loader in React's latest version, add .module to the name of your css files. Once this is done, you can simply use className={styles.className(from css file)} in your main file. This will apply the specific class property to the HTML element.

Make sure to import styles from './mystyle.module.css' at the top of your file for it all to work correctly.

Follow these steps and you're good to go!

Answer №13

Use the class attribute instead of inline styles, for example:

<div class="test">Green</div>

Answer №14

The version of React you are using will determine how you name your CSS and sass files. In the recent versions, the naming convention requires you to use the following format:

[name].moudle.css or [name].moudule.scss.

If renaming the files in this way does not work, you may need to enable it manually. If you started your project with react-create-app and have not ejected it to access all of your config files, follow these steps:

npm run eject 

This will create a config folder. Inside that folder, open your webpack.config files (there should be two). You will need to add the following code snippet to the test: /.css$/ option:

modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'

Your configuration should look similar to this:

 test: /\.css$/,
                    use: [
                        require.resolve('style-loader'),
                        {
                            loader: require.resolve('css-loader'),
                            options: {
                                importLoaders: 1,
                                modules: true,
                                localIdentName: '[name]__[local]__[hash:base64:5]'
                            },
                        },

Make sure to make these changes in both webpack.config files.

Note: Only modify these files if you are certain about what you are doing.

Answer №15

I found that renaming the CSS file to "myfile.module.css" and then importing it with "import styles from './myfile.module.css'" fixed the problem I was experiencing. It's curious why using 'module' in the filename was necessary, but it did the trick.

Answer №16

To properly execute this, make sure you have the latest version of react-scripts, preferably higher than 4.0.0. To do so, run the command

npm install --save react-scripts@latest
. I followed these steps and it worked for me.

Answer №17

When working in a React file, you can easily import the module stylesheet using the import statement. The imported styles can then be assigned to a variable for reference. By setting the className attribute of an element to this variable, you can apply the defined CSS styles to that particular element.

CSS file: module_styles.module.css

    .my_class {
       background-color: blue;
    }

REACT file: component.jsx

    import style from "./module_styles.module.css"

    const MyComponent = () => {
       return (
           <div className={style.my_class}>
                <h1>Example</h1>
            </div>
       )
    }

Answer №18

After spending countless hours trying various methods to make this function in a fresh application I built using the most recent version of create-react-app, which hasn't been updated since 2022, I realized that the conventional solutions provided from that era didn't quite fit my situation. Despite attempts such as creating a typings.d.ts file, ejecting the app and tweaking the webpack files, and other forgotten strategies, none seemed to resolve the issue when attempting to import:

import styles from './zone.module.css';

This consistently prompted an error message in VSCode:

Cannot find module './zone.module.css' or its corresponding type declarations

Resulting in none of the styles being applied as intended.

Eventually, it dawned on me that perhaps the outdated nature of create-react-app was to blame. To test this theory, I initiated a new project with vite, transplanted my .ts file along with ./zone.module.css, and voila - all was functioning seamlessly.

If you find yourself in a similar predicament, my advice is to abandon CRA and opt for vite instead. Not only is it actively supported, but trivial obstacles like this are effortlessly overcome.

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

Assistance needed in obtaining the ID of a specific table row using jQuery

Currently, I am working on an AJAX request using Jquery and PHP. The task involves looping through an array to generate a table. During each iteration, a new ID is assigned to the table row. When users click on the "read me" link, additional content is f ...

Issues with the jQuery slideToggle Method

Can someone assist me in identifying the issue with this code? I am attempting to implement a basic slideToggle functionality! Here is my initial attempt: $("..").slideToggle(..,..,..) This is what my current code looks like: My code: $(document).rea ...

Having difficulty installing npm package from GitHub

Incorporating a workspace into my application "workspaces": [ "firstapp/web", "secondapp" ] Within the second app, in the package.json file, I have included the following dependencies: "anotherapp": &qu ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Div with a fixed position that is displayed on top of another following div

Having trouble with my code on this fiddle: https://jsfiddle.net/0vau6psp/. It seems to be related to the position:fixed property, but I can't seem to solve it. The issue is that the header is overlapping the main content, making it invisible. I want ...

Uploading Files to Amazon S3 Using Axios

I have been working on creating a function that accomplishes the following tasks: Accepts a remote URL as input, Retrieves the file using axios, Streams the file to Amazon S3, And ultimately returns the URL of the uploaded file. I stumbled upon some ass ...

What is the process for converting a string into a map?

Trying to transform a string from this format: string = "John:31,Miranda:28" To this format: obj = { "John" => 31, "Miranda" => 28 } I attempted to do the following: const class = new Map(); array = string.split(","); However, after splitting t ...

Creating a gap in an HTML document with a 'division' element and cascading style sheets

I am struggling to create a blank space between my divs. Despite trying numerous CSS properties such as margin-top, padding-top, and others from various sources online, I have not been successful. The only way I can add space is by using an excessive amou ...

css avoiding code duplication with nested classes

I created a custom CSS class named button.blue: button.blue { background-color: blue; ... } button.blue:active { background-color: darkblue; ... } button.blue:hover { background-color: lightblue; ... } To implement this class, I use the following code: ...

Choosing text input after adding a dynamic HTML row can be done by identifying the specific characteristics

I am currently working on a CodeIgniter project where I have implemented a purchase form that allows users to search for spare parts items using autocomplete in an input text field. The initial search functionality is working fine, but when I try to add a ...

When using html-pdf-chrome to print to an A4 PDF, there appears to be a significant space below the A

In my Laravel project, I am currently utilizing the westy92 / html-pdf-chrome library to convert HTML to PDF. The front-end of my project is based on React. I have defined a series of divs to act as A4 pages: <div id="pdf" className="pri ...

unable to record the input value in jquery

Snippet for HTML code: <div id="Background"> <input id="search-Bar" type="text"> <button id="SearchButton">Search</button> </div> var name = $("#search-Bar").val(); $("#SearchButton").on("click", function() { co ...

Is it deemed as an anti-pattern to establish directives for styling?

Currently, I am in the midst of developing a specialized component UI library for a specific project I'm involved in. This library will consist of unique stylized components with elements that are reused throughout. As I work on this project, I find ...

Incorporating a Unique Identifier to a Marker in GMaps.js

Instead of using the default Google Maps, I decided to use a package called GMaps.js, which is designed to simplify the process. I am currently trying to figure out how to assign an ID to a Marker in GMap.js. Here is what I have so far: map.addMarker ...

Using Django Form with Bootstrap: Incorporating CSS classes and <div> elements

I am currently implementing Twitter Bootstrap with Django to style forms. Bootstrap can enhance the appearance of forms, but it requires specific CSS classes to be included. My challenge lies in the fact that Django's generated forms using {{ form.a ...

Error message occurs when MUI components return Uncaught TypeError

Hi there, I would really appreciate some help. I'm currently working on a react project using MUI and encountering an issue where certain components are not functioning correctly, resulting in an Uncaught TypeError error message. Could someone assist ...

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

How can I identify when a node/express ajax request is received?

I have set up a node/express server that sends the ajax-start.html file. Within this file, there is a script that enables ajax requests to be made to the server. Everything functions correctly in this setup. However, I am looking to enhance this process by ...

The Next.js component only appears after a page reload

Essentially, I have a nested component that is supposed to render with the parent component and it works fine when the server initially starts. However, the issue arises when switching back from another page – some of the nested components disappear. A ...

Is there a way to simulate the change event on a react-select component using react-testing-library?

If I'm unable to directly test the internal components using react-testing-library, how can I effectively test a component that utilizes react-select? For example, if there is a conditional rendering based on the value of the react-select, which does ...