Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS.

  module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',

            query: {
               presets: ['es2015', 'react']
            }
         },
         {
           test: /\.css$/,
           loader:'style-loader!css-loader'
         }
      ]
   }

In addition to the configuration in webpack, css-loader and style-loader have been installed as devDependencies as seen in package.json:

"devDependencies": {
    "css-loader": "^0.28.10",
    "style-loader": "^0.20.3"
}

The challenge arises when trying to apply CSS styles within a React component using className:

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

export default class Foodrecipe extends React.Component {
   render() {
      return (
         <div className={styles.recipe}>
            <h1>Healthy Main Dish Recipes</h1>
         </div>
      );
   }
}

Despite defining simple styles in Foodrecipe.css, changes are not reflecting in the UI when applied through className.

To troubleshoot, applying styles via id (#recipeDiv) instead of className showed successful results, indicating correct CSS file import but potential issues with the className attribute usage.

If you have any insights or guidance on resolving this issue, please share your thoughts. Thank you!

Answer №1

Solution Steps

If you are facing issues importing a css file as styles without utilizing CSS Modules, follow the first solution steps below. For an alternative method using CSS Modules, refer to the second solution provided.

To import the CSS file in a traditional HTML & CSS way, assign a class that contains the desired CSS properties and ensure it is imported using import './Foodrecipe.css'.

import React from "react";
import "./Foodrecipe.css";

export default class Foodrecipe extends React.Component {
   render() {
      return (
         <div className="recipe">
            <h1>Healthy Main Dish Recipes</h1>
         </div>
      );
   }
}

Alternative Solution

For utilizing CSS Modules, include query: { modules: true } in the css-loader. This allows for named imports of CSS files like

import styles from './FoodRecipe.css'
.

index.js

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

export default class Foodrecipe extends React.Component {
   render() {
      return (
         <div className={styles.recipe}>
            <h1>Healthy Main Dish Recipes</h1>
         </div>
      );
   }
}

webpack.config.js

const path = require("path");

module.exports = {
  entry: ["./src/test.js"],

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "engine.js"
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /(node_modules)/,
        query: {
          presets: ["es2015", "stage-2"]
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader"
      },
      {
        test: /\.css$/,
        loader: "css-loader",
        query: {
          modules: true,
          localIdentName: "[name]__[local]___[hash:base64:5]"
        }
      }
    ]
  }
};

Answer №2

Consider bringing in the styles first and then implementing them on the div using className="recipe" instead of: className={styles.recipe}

Make the following adjustment:

import React from "react";
import "./Foodrecipe.css";

export default class Foodrecipe extends React.Component {
   render() {
      return (
         <div className="recipe">
            <h1>Healthy Main Dish Recipes</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 align the sort and search buttons to the right in the Antd Table header?

In my React application, I am utilizing Antd Table and I am interested in repositioning the sort and search buttons to the right side of the Table header. These buttons typically appear on the left side by default, but I have not been able to find a soluti ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Why won't the props pass down to the child component?

I am facing an issue while trying to pass two values as props from a React component "App" to its child "Todo". The values being passed are "title" and "completed" from a json placeholder API. The JSON object is correct and has been verified. The problem ...

What is the process for integrating the node-menu package into my project without utilizing the require statement?

Is there a way to incorporate node-menu into my TypeScript project without using require, like this: const menu = require('node-menu'); Whenever I attempt to import node-menu into my project, I encounter the following errors: ...

The axios.get() method is failing to retrieve the data on the client side

Struggling to set up a LIKE system on my social media app - using React on the client-side and Express on the server-side. I'm attempting to retrieve current LIKE stats by making a GET request with "axios" inside a "useEffect". However, the response d ...

Conceal the popper for one field while revealing the popper for another field

In my current project, I have implemented two text fields positioned next to each other with button adornments at the end. These buttons are used to toggle the visibility of a popper associated with each text field. Additionally, each popper is equipped wi ...

CSS list items do not expand

I have a list with links inside each item and I want the item size to remain fixed regardless of content. Below is the CSS code: .files { display: inline-block; padding: 0; margin: 0 auto; } .files li { display: inline; } .files l ...

How to link external css files in a Node.js project

Can I add an external CSS file in node.js using EJS? I attempted to do so, but encountered difficulties: app.use('/static', express.static('/view')) I included the CSS in EJS like this: <link rel="stylesheet" type="text/css" href ...

How to Create a Bootstrap 4 Footer that is Perfectly Centered

Struggling to grasp Bootstrap 4 specifically, I am focusing on learning how to center my footer, which consists of 2 rows. Despite my efforts, I can't seem to get the entire footer centered properly. Below is the current HTML code I am working with: ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

The functionality of the Jquery mobile panel ceases to work properly when navigating between pages within a multi-page

Within a multi-page template setup in a jQuery mobile application, an issue arises after navigating away from the first page using panel navigation. Upon returning to the first page through another form of navigation, the panel appears "hanged." Upon clos ...

What is the best way to permanently hide a specific button in React.js?

Is there a way to make a button disappear after it has been clicked, and remain hidden even when navigating to different components or pages? Here is the code snippet: <Button className="but" variant="primary" onClick={(e) =&g ...

The worth of the scope is evident, yet it remains undefined when trying to access it

Currently, I am in the process of developing an AngularJS directive. However, I have encountered an issue where a scope variable appears to be undefined when attempting to access it. Interestingly, upon printing out the scope, it is evident that the variab ...

How well are DOM Mutation Observers supported across different web browsers?

I attempted to search for a solution by Googling, but was unsuccessful in finding an answer. Does anyone know if there is a compatibility matrix available for this feature that works across all browsers? In case someone is interested in the answer, here ...

Upgrading to NPM version 7 or higher: A guide to effectively installing packages using the "lockfileVersion" parameter: 1

After upgrading NodeJS to version 16, I noticed that NPM version 8 is now included. This means that when I install packages, the package-lock.json file is generated with a "lockfileVersion": 2. However, I prefer the older format of "lockfileVersion": 1. ...

JavaScript causing attribute() variable to malfunction in CSS animation

I am attempting to implement a CSS animation using three files. Below is the HTML file: <html lang="en"> <head> <link rel="stylesheet" type="text/css" class = "tag" href="../css/style.css" ...

Using Styled components and react-router-dom v6 to emphasize the active navigation link upon clicking

I'm just starting out with react and I am trying to figure out how to keep my hover style active while the current page is open. I think I need to set a condition but I am not sure how. const StyledLi = styled.li` `list-style: none; displa ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

What is the method for displaying html files in a POST request?

This is the code snippet I am working with: app.post('/convert', function(req,res){ var auxiliar = "somo Ubuntu command line(this works)"; exec(auxiliar, function(err, stdout, stderr){ if(err){ console.log ...

Social Engine is incapable of analyzing the HTML code

Currently working on a website using Social Engine 4.8.9 version that is still in development mode. Upon inspecting the html code with the chrome inspector, I find it incredibly complex to decipher. For instance, when I click on the login page link http:// ...