React css modules to enhance styling in your web project

I am in the process of incorporating a CSS module into the login component. Currently, I have a style.css stylesheet located in the src/styles folder, which is responsible for loading global styles. However, I now want to customize the login component by adding a login.css file within the components/login directory:

.button {
  background-color: black;
}

The code snippet from my LoginPage.js component is as follows:

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

class LoginPage extends React.Component {
  render() {
    return (
      <div className="jumbotron col-md-6 col-md-offset-3">
        <div className="container">
          <form name="form">
            <div className="form-group">
              <label htmlFor="username">Username</label>
              <input type="text" name="username" className="form-control" required />
            </div>
            <div className="form-group">
              <label htmlFor="password">Password</label>
              <input type="password" name="password" className="form-control" required />
            </div>
            <div className="form-group">
              <button className="btn btn-primary">Login</button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default LoginPage;

My webpack configuration is throwing the following errors:

src\components\login\LoginPage.js (2/2)
  ✖  2:20  Parse errors in imported module './Login.css': Unexpected token . (1:1)  import/namespace
  ✖  2:20  Parse errors in imported module './Login.css': Unexpected token . (1:1)  import/default
  !  2:20  Parse errors in imported module './Login.css': Unexpected token . (1:1)  import/no-named-as-default
  !  2:20  Parse errors in imported module './Login.css': Unexpected token . (1:1)  import/no-named-as-default-member

This is an excerpt from my webpack.config.js:

import webpack from 'webpack';
import path from 'path';

export default {
  debug: true,
  devtool: 'inline-source-map',
  noInfo: false,
  // Remaining content would be same.
};

When trying to implement the CSS module in JSX, I encountered a problem:

 <div className="form-group">
   <button className={styles.button}>Login</button>
 </div>

src/components/login/LoginPage.js: JSX value should be either an expression or a quoted JSX text (19:32)

Any guidance on correctly setting up CSS modules for React would be appreciated.

EDIT:

After addressing the error related to loading the class, the updated syntax looks like this:

<div className="form-group">
  <button className={styles.button}>Login</button>
</div>

Now, although the CSS is successfully loaded, the webpack errors and warnings persist.

Answer №1

One issue is that you are trying to incorporate raw CSS into your JavaScript code without converting it to ICSS beforehand.

To resolve this, ensure your webpack loader is configured for CSS modules. You can achieve this by including the modules option and possibly a template for the localized class names.

Update your CSS loader configuration as follows:

{test: /(\.css)$/, loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'}

This configuration instructs webpack to preprocess the CSS into ICSS prior to import, transforming it into a JS object that defines how to match your button class with the dynamic localized class name like LoginPage__button___ab123

You can then apply classNames using the imported object as you initially attempted, though the interpolated string might not be necessary unless adding multiple classes.

<button className={styles.button}>Login</button>

Answer №2

After reviewing the error message, it is recommended to structure the code in the following manner:

<div className="form-group">
  <button className={styles.button}>Login</button>
</div>

The reason for this adjustment is that strings enclosed by `something ${var}` are considered as variables and require additional computation before being converted into ES5 JavaScript code (while strings within single or double quotes like 'rawString' or "rawString2" do not).

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

All hail the powerful nodejs server.listen() function, the gate

My journey into learning about nodejs servers and websockets has just begun. Currently, I am exploring a server written in javascript using socket.io and express. var app = require('express')(), server = require('http').Server(app) ...

What steps can I take to minimize the flashing of this fixed navigation bar?

My fixed navigation bar fades out when scrolling down the page and reappears when scrolling up, which all works well. However, I have noticed that if I do this very quickly with short movements, around 20 times, it doesn't have enough time to complete ...

The HTTP request is malfunctioning in a different location

I'm facing an issue where my code works in the w3schools code editor, but not on localhost or cpanel host. When I try to run it on another host, it gives me a bad request and doesn't return the answer. Here is the code snippet that I am working ...

Produce HTML content onto Google Drive Documents using JavaScript

Currently, I am working on a project that requires me to render the HTML form output in a new Google Docs document (a Word file, not a spreadsheet). Despite my efforts to find information online, all I can come across is related to spreadsheets. The main ...

The condition is not functioning properly when the array's length is greater than 1

Within the primary controller, there is an if-else statement: var entity = shareDataService.getModalEntity(); if (entity = "NULL" || entity.length === 1) { myDataPromise = getDataService.getDataFromREST(security); console.log("HERE") } else { ...

The various options in the dropdown menu are descending in order

I am currently facing an issue with a dropdown menu that contains the list of products offered by our company. Specifically, one of the product names, Hotel Management Solutions, is appearing on multiple lines instead of a single line in the dropdown menu. ...

How to convert DateTime to UTC in TypeScript/JavaScript while preserving the original date and time

Consider the following example: var testDate = new Date("2021-05-17T00:00:00"); // this represents local date and time I am looking to convert this given Date into UTC format without altering the original date and time value. Essentially, 2021-0 ...

Tips on determining the type of DOM element for CSS Selector adjustment

In this case, $self is not returning the expected result and I am getting "undefined". To adjust the CSS selector to correctly target the desired element, I need to determine which element type I am dealing with. Is it the "ul", "li", or "a" element? Whil ...

Ways to increase the size of a div to match the maximum height of its parent container

My current project involves using an angular dialog layout where the API to open and manage the dialog comes from a separate library. The dialog's parent container has a max-height attribute, meaning the dialog's height is determined by its conte ...

Scrolling to specific ID scrolls only in a downward direction

I have been using fullpage.js for my website and I am facing an issue. When I create a link and connect it to an id, everything works perfectly. However, I am unable to scroll back up once I have scrolled down. Here is the HTML code: <a href="#section ...

What is the best way to merge an array into a single object?

I have an array object structured like this. [ { "name": "name1", "type": "type1", "car": "car1", "speed": 1 }, { "name": &q ...

The HTML element in the side menu is not adjusting its size to fit the parent content

Update: What a day! Forgot to save my work... Here is the functioning example. Thank you for any assistance. I have set up a demo here of the issue I'm facing. I am utilizing this menu as the foundation for a page I am developing. The menu is built ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

Guide on toggling the expansion and collapse of antd TreeSelect items when a button is clicked

I recently started using the antd library to develop my website. I have successfully implemented the TreeSelect component to display nested options. However, I am currently facing an issue: I am attempting to expand and collapse TreeSelect items when a b ...

Inline display with automatic margin

I am seeking guidance from someone with more experience to help identify the source of this margin. Your assistance is greatly appreciated! https://i.stack.imgur.com/46k7k.png Below is the CSS code in question: .logo-icon { background-image: url(&ap ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Tips for customizing fonts in react-pdf

I am having difficulty in changing fonts within react-pdf. // Register Font Font.register({ family: "Roboto", src: "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf" }); The default f ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Stop Bootstrap popover from being displayed before it is hidden using .hide()

I am attempting to control the display of a popover based on a certain condition. <form class="submit-form" action="{% url 'search' %}" method="post"> {% csrf_token %} ...