"Error message stating 'Unresolved variable' occurs in the code while trying to assign className={styles.nameOfClass

My current task involves adjusting the style of a button in ReactJS using the "className" property. However, I encountered an error message in WebStorm stating "Unresolved variable nameOfClass," and the desired style changes did not reflect when running webpack and opening the page on localhost. Despite trying different approaches to import the CSS file and naming conventions, the issue persists.

Below is the code snippet for the React Component class:

import * as React from "react";
var styles = require('./Roster.css');
export class Roster extends React.Component<{},{}> {

    render() {
        return (
            <div>
                <button className={styles.nameOfClass} type="button" >Players</button>
            </div>
        );
    }
}

The content of the Roster.css file can be seen below:

.nameOfClass {
    background-color: #ff0000;
}

Furthermore, the configuration settings found in webpack.config.js are crucial:

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "./dist/bundle.js",
    },

    // Sourcemaps enabled for easy debugging of webpack's output.
    devtool: "source-map",
    
    // Specify resolvable extensions
    resolve: {
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    module: {
        loaders: [
            { test: /\.tsx?$/,
              loader: "ts-loader"
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'),
            }
        ],

        preLoaders: [
            { test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    plugins: [
      new ExtractTextPlugin('styles.css', { allChunks: true })
    ],

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    },
};

Answer №1

No need to import the styles file.

import * as React from "react";

export class Team extends React.Component<{},{}> {

    render() {
        return (
            <div>
                <button className="teamName" type="button" >Players</button>
            </div>
        );
    }
}

Include your css file:

.teamName {
    background-color: #ff0000;
}

Answer №2

Should be something along these lines:

import * as React from "react";

export class TeamRoster extends React.Component<{},{}> {
    render() {
        return <div>
            <button className="teamButton" type="button">Team Members</button>
        </div>
    }
}

You are limited to importing only typescript/javascript files, not css files.

Consider using tools like css-modules, or exploring solutions like Radium and reactCss for React/CSS integration.

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

Arrangement: Div beside vertically-aligned hyperlinks

Example code: p { color: red; } span { font-weight: bold; } <p>This is a paragraph.</p> <p>Another paragraph here.</p> <span>Bold text</span> This is the desired outcome: https://example.com/image.png It&ap ...

Creating side panels on the left and right using CSS and HTML

I am looking to design a website where users can open sidepanes from both the left and right sides. I am not proficient in JavaScript and would prefer a solution using only CSS and HTML. While browsing, I came across a website that achieves what I want thr ...

Discover the seamless process of dynamically adjusting metadata to reflect current state values within the Next.js app directory

Exploring the app directory within Next.js version 13, I came across a change in the official documentation where they have replaced the old head method with metadata. Initially, I thought this feature was only available on page or layout components. Now, ...

Using div elements to mimic the layout of tables with row spans

<div class="container"> <div class="box1">1</div> <div class="box2">2</div> <div class="box3">3</div> </div> .box1 { border: 1px solid red; float: left; width: 20px; } .box2, .box3 { ...

Issues with Bootstrap's center-block functionality

I'm having trouble centering the navigation in my WordPress template that uses Bootstrap. I've tried using the center-block class on different elements, but the menu items are still aligning to the left. I even created a custom class in my custom ...

Editable Material Table in React with Date Picker and Column Warnings

I have been working on enhancing material-table functionality. My goal is to incorporate additional columns into the data table. One of the requirements is to introduce a date time picker in an editable column, while keeping another column non-editable. T ...

Use CSS to create a fullscreen animation for an element

Is there a way to animate a div element so that it expands to fit the screen when clicked without specifying an initial position? I need the div to be able to adjust dynamically within the screen. .box { width: 80px; height: 80px; background: red; ...

How to remove outer quotes from JSON data in Reactjs after using JSON.stringify

When using JSON.stringify on a Json data, I noticed that the resulting string includes double quotes at the beginning and end. For example: x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}} After using JSON.stringify, the result looks like t ...

Theming the Appbar in a React Mui application

Is it possible to theme an MUI AppBar without using styled components or other style APIs? I am new to theming and would like to know how to do this. palette.js import { createTheme } from '@mui/material/styles'; const theme = createTheme({ ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

Encountered an issue following deployment to Heroku (Application error)

Introduction I recently created a Login form for my project. The frontend is deployed on Netlify at this link, and the backend is hosted on Heroku which can be accessed here. To view the backend logs, click here Here is a snippet of my index.js file: co ...

Retrieving Data from Repeated Component in Angular 6

Need Help with Reading Values from Repeating Control in Angular 6 I am struggling to retrieve the value of a form field in the TS file. Can someone please assist me with this? This section contains repeating blocks where you can click "add" and it will g ...

It appears that the box-shadow feature is malfunctioning on Internet Explorer 8

Hey there, I'm having an issue with the box shadow not displaying correctly in IE 8. Here's my CSS code: .lt-ie9 .imageonHover:hover { box-shadow:1px 1px 5px 5px #E7E0E7; border-radius:3px; zoom: 1; filter: progid:DX ...

How can we best utilize Testcafe Selector functions?

Is it considered a single query on the DOM when you chain selectors and functions like this? Selector('[data-testid="somevalue"]') .nth(0) .find('div') .withAttribute('class', 'someclass') ...

In MUI React, the opacity of the placeholder is customizable and can be easily adjusted. This allows for the placeholder to be hidden

Currently, I am facing an issue with a filled variant TextField from Mui React. I have tried to modify it using theme components, but the placeholder text becomes hidden when the field is not focused. See here for Before Focus And here for On Focus I hav ...

Unleashing the power of Sass and CSS in your Next Js project

Trying to incorporate sass and css modules into my next.config.js has been challenging due to an error I keep encountering: Failed to compile. ./node_modules/@riskalyze/react-ui/node_modules/@riskalyze/calendar/assets/index.css Unknown word (1:1) > 1 ...

An exploration of the functionality of the String.fromCharCode method when used with a mobile keyboard in an HTML input

I'm looking to retrieve the keyboard key code and translate it into characters. I've been utilizing the String.fromCharCode javascript method, but it seems to only be effective with a computer keyboard and not functioning properly with a mobile k ...

When floated to the right, the element is being pushed onto the next line in Firefox

Within a div, there are four elements. I specifically want the last element to be positioned on the far right, so I applied float: right to it. However, in Firefox, the last element gets pushed to the end of the next line instead. This issue does not occ ...

Having trouble with setting an image as a background in CSS for Nativescript on iOS?

In my NativeScript app, I am trying to set an image as the background using the CSS property background-image: url("res://ic_more"). It works perfectly on Android, but unfortunately, it does not display on iOS devices. I have confirmed that the image is l ...

Adjusting the dimensions of the canvas leads to a loss of sharpness

When I click to change the size of the graph for a better view of my data in the PDF, the canvas element becomes blurry and fuzzy. Even though I am using $('canvas').css("width","811"); to resize the canvas, it still results in a blurry graph. I ...