Skip to content Skip to sidebar Skip to footer

CSS ClassName Not Reflecting When Using CSS Modules In My React Component

This is the module section of my webpack.config.js file I have also installed css-loader and style-loader, this is how the package.json file looks - This is my react component wh

Solution 1:

Solution 1

You are trying to import css file as styles without using CSS Modules. Check Solution 2 if you want to do it like that.

So just like you do in vanilla HTML & CSS, just give a class whose css property you want to use & make sure you just import it like 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>
      );
   }
}

Solution 2

Use query: { modules: true } in css-loader to use it as CSS Modules, i.e, named import for a css file 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]"
        }
      }
    ]
  }
};

Solution 2:

Try importing the styles then apply them to the div with className="recipe" intead of: className={styles.recipe}

Do this:

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>
      );
   }
}

Post a Comment for "CSS ClassName Not Reflecting When Using CSS Modules In My React Component"