Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can't seem to make it work.

The reason for this dilemma is because I am developing a custom UI library for others to utilize. Users will only need to download HelloWorld.tsx and HelloWorld.module.css (which provides a default background style). They should be able to override the background by applying their own class when using the component. So, I'm trying to figure out the best approach to achieve this.

Take a look at the example below:

// HelloWorld.tsx
import styles from './HelloWorld.module.css'

export default function HelloWorld({className}) {
    return <div className={`${styles.Container} ${className}`}>Hello world</div>;
}
/* HelloWorld.module.css */
.Container {
  background-color: green; /* default component style to be overridden by users */
}
/* global.css */
.danger-container {
    background-color: red;
}

Now, I want to use the component like this:

<HelloWorld className='danger-container' />

Unfortunately, the local style is not being overridden and the container remains green.

I've been resorting to using !important as a last resort, but I've been advised against it as bad practice. I'd prefer if users of the library didn't have to rely on !important to override my default styles.

Please help me determine the best way to address this issue.

Thank you in advance.

Answer №1

Both of your CSS statements have equal specificity levels, so the one that appears later in the cascade will take precedence. In this scenario, .Container wins out. If you want .danger-container to override .Container, you'll need to make it more specific. There are a few ways to accomplish this:

.danger-container {/* 0,1,0 */
    background-color: red;
}

.Container.danger-container {/* 0,2,0 */
    background-color: blue;
}

body .danger-container[class] {/* 0,2,1 */
    background-color: pink;
}

.Container {/* 0,1,0 */
    background-color: green;
}
<div class='Container danger-container'>Hello world</div>

Another option is to assign an ID to your element, as IDs hold higher specificity than classes.

#danger-container {/* 1,0,0 */
    background-color: orange;
}

.Container {/* 0,1,0 */
    background-color: green;
}
<div class='Container' id='danger-container'>Hello world</div>

Here are some resources to help you understand CSS Specificity better:

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 button is only partially visible

My HTML code for a small web app has a button that says "ok," but it's too tiny to display the text fully. I wonder if I'm missing something with the span element? How can I enlarge the button so that it's bigger and shows the entire "ok" ...

Swapping icons in a foreach loop with Bootstrap 4: What's the most effective approach?

I need a way to switch the icons fa fa-plus with fa fa-minus individually while using collapse in my code, without having all of the icons toggle at once within a foreach loop. Check out a demonstration of my code below: <link rel="stylesheet" href= ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

Guide to importing Bootstrap 5 bundle js using npm

Having some issues with implementing Bootstrap5 and NPM. The website design is using bootstrap, which works fine, but not all the JavaScript components (dropdowns, modals, etc). I want to figure out how to import the Bootstrap JS bundle without relying on ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Exploring the process of sending JSON responses through Express

I recently started working with node/express. My express app has a single post route ('/'), which is designed to retrieve information about GitHub users based on their usernames. For instance, when I make a post request like this { "develop ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

"Troubleshooting: Jquery Draggable Function Fails to Execute

I'm currently working on a JSP page where I am attempting to make the rows of a table draggable. Despite multiple attempts and combinations, I have been unable to make any elements draggable. The rows are appended after an AJAX call, but still no succ ...

Ways to verify when leaving the webpage

After spending an excessive amount of time searching for this information, I finally figured it out. So here you have it, I'm sharing the steps to create a custom "ARE YOU SURE YOU WANT TO LEAVE THIS PAGE?" dialog. ...

Alert: Mouse Exiting Window - Moodle Prompt

I have created an online exam using the Moodle platform, coded in PHP. I am now looking for a way to prevent test-takers from navigating away from the test by implementing a mouseover pop-up. Below is the code I have for triggering an alert pop-up when th ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...

Property that is dynamically populated based on data retrieved from an external API

My template relies on an API call (Firebase) to determine the return value of my computed property, which in turn decides whether certain elements are displayed. However, I've noticed that my computed property is not reactive - its value in the templ ...

What is the method for obtaining the socket object for individual users who are connected in Node.js?

I am currently using socket.io to send notifications to users. I have set up a listener that is monitoring for a specific event. myEvent.watch ((res,err)=> { if (!err) { let id = res.userID; let msg = res.msg; //to imple ...

Unable to retrieve JSON data using jQuery

When working with jQuery to retrieve JSON data, I encountered an issue. After storing the data in a variable named "ajaxResponse," attempting to access specific data points resulted in an error stating that ajaxResponse.blah is not defined. Interestingly, ...

How to style a div's height responsively behind a circle using CSS

Can a CSS pattern be created with responsive design, ensuring that the background line is always in the correct position and height regardless of window size? https://i.sstatic.net/27Tf2.jpg ...

Ways to transmit information from a React application to a Node server

As a Nodejs beginner, I am using the rtsp-relay library for live streaming. Currently, it is working in the frontend when the URL is included in the server proxy object like this: rtsp://.....@..../Stream/Channel/10. However, I want users to be able to inp ...

Is the useNavigate() function failing to work consistently?

Currently facing an issue while working on a MERN Web App. When logging in with an existing account, the backend API call returns user properties and a JWT Token. Upon saving it, I use the navigate function to redirect the User to the homepage. Everything ...

Mastering socket emission and disconnection in reactjs

When using the onchange function, I am able to open a socket and emit/fetch data successfully. However, a new socket is opened on any event. I need to find a way to emit data from the same socket ID without opening a new socket each time. Could you pleas ...