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

The function "xml find" does not exist

After successfully running the following ajax call, I encounter an issue: $.ajax({ url: "services/orders/<%=OrderServices.Action.BULK_SUPPLIER_DISCOUNT%>", data: params, complete: function(xhr) { i ...

Titanium: Warning upon initiation

Is it feasible to trigger an alert immediately after a window finishes loading? I am using a create window function followed by an alert message, then returning. function NewView() { var self = Ti.UI.createWindow({}); alert("A basic or confirm al ...

Vuex was unable to locate the required dependency

Currently, I'm following an instructional video that incorporates Vuex. As shown in my package.json dependencies, I have installed Vuex: { "name": "blabla", "version": "1.0.0", "description": "blablaa", "author": "blabla", "private": true, ...

Packages have gone astray post node_modules scrub

I encountered an issue with npm run watch getting stuck at 10%, so I took the step of deleting the node_modules directory and package-lock.json. However, it seems that I may have installed modules using npm install without the --save-dev option. Even after ...

Learn how to insert JavaScript code into the head of an iframe using jQuery

My goal is to inject javascript code into the head of an iframe using jquery with the code provided below. var snippets_js='<?php echo $snippets_javascript;?>'; var scriptjs = document.createElement("script"); scriptjs.type = "text/j ...

Ensuring that md-select(s) created through ng-repeat are linked to the same model

<div ng-repeat="(key, value) in dataSet | groupBy: 'partner.partnerName'"> <md-select ng-model="userName" placeholder="{{ key }}" class="partnerUser" > <md-option >{{ key }} </md-option> <md-option ng-repe ...

Checking if children have certain text using jQuery

My task involves filtering an HTML table. In order to accomplish this, I have created an 'each' callback for all 'tr' elements and check if any of their children contain a specific pattern. $("#filter").keypress(function() { var fi ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...

Creating a subtle vanishing popup dialog using only CSS (no reliance on jQuery)

Is there a way to add a fade effect to my simple pop-up image using CSS? I've tried various transition properties, but nothing seems to work. Any suggestions would be appreciated. Thanks! ...

Center-align the text in the navigation bar

Is there a way to center the text within my navigation and ensure it remains centered across all resolutions (left at 1920x1080, centered at 1420)? I understand that much of this code is inefficient and not working correctly, but for now I just want to fi ...

What's the best way to make a toast notification appear when an API call is either successful or encounters

Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application... My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call. While a ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Implementing Mouse Scroll Click Functionality in ASP.NET with C# (Without JavaScript)

How can I add a Mouse Scroll Click (Middle Button) event in ASP.NET and C#? I have already looked into the MouseWheel Event, but it did not provide the solution I was looking for. This is the order in which mouse events occur: MouseEnter MouseMo ...

How can I line up elements in different divs when the width is adjusting based on the window size?

Trying to align a search input and a result element in separate containers when the window size changes. Looking for a solution without using Javascript. One window size: A smaller window: Currently utilizing but facing challenges with responsive desig ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

What is the best way to showcase an item from an array using a timer?

I'm currently working on a music app and I have a specific requirement to showcase content from an array object based on a start and duration time. Here's a sample of the data structure: [ { id: 1, content: 'hello how are you', start: 0 ...

Having trouble retrieving a value from the $http promise, causing the code within the then() function to not run as expected

In the past, I encountered a challenge with the $http service which I managed to solve by creating a dedicated service for handling my requests. However, as my requests grew larger, this solution started to seem inefficient. Instead of just assigning a sim ...

Is Flash consistently positioned above the other elements? Can it be corrected using CSS

Hey there, I just uploaded a video from YouTube onto my website and noticed that the footer, which is fixed, is being overlapped by the video. Is there any way to resolve this issue? Perhaps some CSS tricks or hacks? Any assistance would be highly appreci ...

AngularJS Cascading Dropdowns for Enhanced User Experience

There is a merchant with multiple branches. When I select a merchant, I want another dropdown list to display the data from merchant.branches. The following code does not seem to be fixing the issue: <label>Merchant:</label> <select ng-if= ...