CSS-loader imported styles failing to function properly

Constructing a React 16.4.0 application with Bootstrap 4.1.1.

My approach involves using css-loader alongside webpack to generate personalized stylesheets for each component within my app.

Despite my efforts, I am facing the issue where my custom styles are not being applied. Initially, I suspected that the problem stemmed from Bootstrap's styles taking precedence. However, even when incorporating an element that exists independently of any Bootstrap styling, my custom styles fail to manifest.

As illustrated in the following example:

Sidebar.js component:

import React from 'react';
import classes from './Sidebar.css';

const sidebar = (props) =>  {
    console.log('classes.red:', classes.red);
    return (
        <div>
            <h3 className={classes.other}>Testing Stylesheet</h3>
            <nav className="col-sm-3 col-md-2 hidded-xs-down sidebar" id={classes.red}>
                <ul className="nav flex-column">
                    <li className="nav-item">
                        <a className="nav-link active" href="#">
                            FF1493
                        </a>
                    </li>
                    <li className="nav-item">
                        <a className="nav-link active" href="#">
                            FF4500
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    )
}

export default sidebar;

Here is the straightforward stylesheet utilized:

#red {
    background-color: rgba(214, 21, 21, 0.842)
}

.other {
    color: green;
}

Within Sidebar.js, the imported 'red' style is logged via console. The browser's console outputs the following: classes.red: Sidebar__red__2-sUP, correctly displaying the unique identifier.

For those who may require additional information, below is my webpack configuration:

const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');

const SRC_DIR = path.join(__dirname, '/client/src');
const DIST_DIR = path.join(__dirname, '/client/dist');

module.exports = {
    entry: `${SRC_DIR}/index.jsx`,
    output: {
      path: path.resolve(__dirname, 'client/dist'),
      filename: 'bundle.js',
    },
    module: {
      rules: [
        {
          test: /\.jsx?/,
          include: SRC_DIR,
          loader: 'babel-loader',
          query: {
            presets: ['react', 'es2015'],
            plugins: ['syntax-dynamic-import'],
          },
        },
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract(
            Object.assign(
              {
                fallback: {
                  loader: require.resolve('style-loader'),
                  options: {
                    hmr: false,
                  },
                },
                use: [
                  {
                    loader: require.resolve('css-loader'),
                    options: {
                      importLoaders: 1,
                      minimize: true,
                      modules: true,
                      localIdentName: '[name]__[local]__[hash:base64:5]'
                    },
                  },
                  {
                    loader: require.resolve('postcss-loader'),
                    options: {
                      ident: 'postcss',
                      plugins: () => [
                        require('postcss-flexbugs-fixes'),
                        autoprefixer({
                          browsers: [
                            '>1%',
                            'last 4 versions',
                            'Firefox ESR',
                            'not ie < 9', 
                          ],
                          flexbox: 'no-2009',
                        }),
                      ],
                    },
                  },
                ],
              }
            )
          )
        },
      ],
    },
    resolve: {
      extensions: ['.js', '.jsx']
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('development'),
        },
      }),
      new ExtractTextPlugin("styles.css"),
    ],
  };

Could the omission of certain elements in webpack.config, such as sourceMap: shouldUseSourceMap, under options and extractTextPluginOptions, be contributing to the issue at hand?

I commented out these sections while configuring webpack due to encountering errors during setup and lacking clarity on their specific functions. As I continue to familiarize myself with webpack, I incorporated some configuration settings from a previous project developed using Facebook's create-react-app.

Your insights and suggestions would be greatly appreciated. Thank you in advance! Mike

Answer №1

Here's what you need to do:

import './Sidebar.css'; //make sure not to name the import

After importing, apply the class to your element like this:

<h3 className="other">Testing Stylesheet</h3>

(Additionally, as per @Leo's recommendation, check Dev Tools and search for the css to ensure it is being sent to the browser)

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

React Component not retaining its value

I am currently facing an issue with a React component where I need to read a file from an Upload and pass the contents onto a child component for display. Although I can successfully read the file contents using FileReader and see the results in the cons ...

Problem with Bootstrap loading state when certain input fields are required

Just starting out with Bootstrap 3 and looking to integrate the loading state button function into my form. I've set up an input field with the required option as shown below. <form> <input class="input" name="title" type="text" required / ...

Ways to include extra information in a request when uploading images using Django's CKEditor?

On my website, I am utilizing django-ckeditor to allow users to input rich text content. Each webpage on the site represents a unique document identified by an id. For instance, two different documents will have separate webpages with URLs like - exampl ...

Utilizing custom emitted events as props for a newly created component within VueJs

My application comprises of: A component called <consl :output="output" @submit-to-vue><consl> that includes an input triggering a submit() method when the enter key is pressed. <div> <output v-html="output"></output> ...

Lately, I've been coming across mentions of "myApp.controllers" and "myApp.modules" in Angular JS. Can anyone explain the significance of these terms?

Recently, I've come across code that looks like this: angular.module('app.controllers') This pattern has appeared in a few tutorials I've read. However, the purpose of the .controllers within the module name is unclear to me. I'v ...

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Upon loading the page, include a class to a specific element within an AngularJS ng-repeat function by evaluating the content of a JSON object

I have a group of buttons that are generated from a json object. Whenever a user clicks on a button, it changes color (referred to as the selected color) using the ng-class directive with bootstrap classes. If the same button is clicked again, it reverts b ...

Tips for ensuring the page remains functional with the signOut feature even after a refresh

I am facing an issue with my website. On the home page, I have a sign-in and sign-out column. Then, on the user page, there is a sign-up form. When I sign out, it works fine but upon refreshing the page, it still shows as if the user is not signed out. Can ...

Gradually make the table row and its contents disappear as you scroll, based on how hidden the row is within the containing div

Uncertainty clouds my mind as to the practicality of this approach, the potential performance implications, and the frequency of scroll events firing to make this technique viable. Nevertheless, within a fixed height div (overflow-y: auto) lies a table. M ...

Is it possible to optimize a page rendered with getServerSideProps to partially display before the completion of getServerSideProps?

I have a simple component that fetches user data from a Next API. I am attempting to transfer the fetching process from the client to the server using getServerSideProps, but I am struggling to do so in a non-blocking manner. The endpoint /api/users is a ...

Deselect an HTML checkbox using a corresponding label's "for" attribute

Below is the html code I am using to display a checkbox with an image: <div class="testClass"> <input id="111" name="compare_checkbox" type="checkbox" /> <label for="111"> <i class="icon" aria-hidden="true"&g ...

Performing a map or foreach function on an array of objects limited to the first 5 objects

I need to iterate through an array of objects, but I only want to loop through the first 5 objects and then stop. What is the most efficient way to achieve this? [ {"visibility": 10000,}, {"visibility": 10000,}, {"visibilit ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

The browser is opting to download the HTML file rather than displaying it

Recently, I set up a server using Node.JS express where I specified the location of an HTML file in the public folder. app.use(express.static(__dirname + '/public')); app.listen(8080); In previous projects, this setup worked seamlessly. However ...

Encountering problems with ajax technology

As a newcomer to Laravel and Ajax, I am facing an issue with displaying the state of the selected country in a dropdown list. Although the data is successfully fetched from Laravel and received through Ajax, I am struggling to dynamically add it to the H ...

Encountering a problem with node-sass during asset compilation - npm

I encountered an issue while running npm run prod npm run prod > @ prod /opt/atlassian/pipelines/agent/build > encore production Running webpack ... ERROR Failed to compile with 2 errors4:15:08 PM error in ./web/assets/src/scss/styles.scss Module ...

Different placeholder text rendered in two text styles

Can an input box placeholder have two different styles? Here's the design I have in mind: https://i.stack.imgur.com/7OH9A.png ...

Enable the script tag with the type "module" only under certain conditions

Attempting to dynamically enable script tags in HTML using the code below does not yield the expected results. function loadScript() { document.querySelectorAll('script[type="text/skip-hydration"]').forEach((script) => { script ...

How to toggle the visibility of a div with multiple checkboxes using the iCheck plugin for jQuery

I customized my checkboxes using the icheck plugin to work with both single and multiple checkboxes, including a "Check all" option. Here is an example of how it looks in HTML: HTML : <div>Using Check all function</div> <div id="action" c ...

Creating a Faux Font-Icon Effect Using CSS and PNG

I am looking for a way to change the color of a transparent, grey-scale PNG icon as easily as changing the color of a font icon. More details: The PNG icons have both outer transparencies and inner white areas for the actual symbol, along with a slight gr ...