React - Prevent conflicts by overriding existing styles with a new class

I've come across many discussions on this topic, but nothing has worked the way I need it to. In my React component, I'm passing className as a prop. I also have a Higher Order Component (HOC) that takes a component and default style, then returns a component where you can input a new style, like this:

function withCombinedStyles(WrappedComponent, defaultClassName) {
    return ({className: newClassName, ...rest}) => {
        const className = combineClassNames(newClassName, defaultClassName);

        return <WrappedComponent className={className} {...rest} />;
    };
};

At the moment, the combineClassNames function simply combines the strings. My goal is for the newClassName to always take precedence over any conflicting styles in the defaultClassName, while still retaining the old ones. Currently, one style seems to dominate the other without any clear order - the arrangement of defaultClassName and newClassName doesn't seem to matter. How can I achieve this? Although I am currently using CSS modules, the project is small enough for me to consider switching to another technology if needed to achieve the desired outcome (though I would prefer to stick with CSS modules and find a React-specific solution).

I could use !important, but that would limit adding a third className and potentially complicate future style extensions.

Answer №1

When working with CSS in JS, the order of declarations is important as it determines specificity. If newClassName has less specific declarations compared to defaultClassName, then the more specific declarations in defaultClassName will take precedence. Ensuring that the desired statements are more specific can often resolve CSS conflicts.

Tools like specificity calculators can be helpful in understanding this concept better.

If you opt for inline CSS-in-JS styles, the following approach could be effective:

function withCombinedStyles(WrappedComponent, defaultStyles) {
    return ({styles: newStyles, ...rest}) => {
        return <WrappedComponent style={{...defaultStyles, ...newStyles}} {...rest} />;
    };
};

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

Utilize Material UI and React JS to showcase specific row data in a different component

I am encountering an issue with retrieving data from a Data Grid (or XGrid) to showcase in another component on the page. In the code provided below, you can observe that I am fetching data from a local database and displaying it in a Data Grid. My object ...

Adjust the size of a Highcharts chart before printing

I'm facing an issue with a chart that doesn't have a specified height or width. My goal is to print the graph in a taller and larger size when I click on the print button. I attempted to use setSize() function, but since there are no original di ...

I am currently working on making my social items more responsive, however, I am encountering some issues. Any ideas or suggestions on how to resolve this

Find my resume project on GitHub at https://faizan-ul-hasnain.github.io/Resume-Project-/ and let me know how to improve it. Visit my resume project here ...

What is the best way to create a flexible canvas/grid/row/column that can adapt to changes in browser width and height, all while maintaining its aspect ratio

As someone new to the world of JavaScript, CSS, and HTML, I am eager to learn how to create a game site with multiple games. However, I am feeling lost when it comes to determining the right direction to take. My goal is to develop a game board that can ad ...

Is there a way to extend this section to fill the entire screen height without any white space at the bottom?

We've been working on extending the content to the full height of the screen, but no matter what we try, there's always some white space lingering at the bottom. Any suggestions on how to fix this issue? section { height: 100vh; background ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I ...

I am having trouble setting margins for a sticky position in a WordPress website

Can someone help me reposition the left-sidebar with a sticky top to be below the main header when scrolling down? Adding margin-top to sticky-top under col-sm-1 is not working. <style> .col-sm-1 .sticky-top { margin-top: 50px} </style> ...

What is the reason behind the required designation for the props onClose and onOpen in the SwipeableDrawer component of Material-UI?

It seems that the onOpen and onClose properties aim to incorporate elements of the Observer pattern. But why is it necessary for a client using the SwipeableDrawer component who does not wish to observe these events to still provide values for these prope ...

How can you showcase a background on both the top and bottom of a div at the same time? #dual

Trying to add a gray rectangle (indicated by the red circle) at both the top and bottom of a div that contains thumbnails. This div may have 2 or 3 rows of thumbnails. Image: Current code snippet: .jq_thumbnails { background: url("/site_media/static ...

I can't seem to locate the console within IntelliJ IDEA

I'm currently building a simple app using React in Intellij IDEA and have run into an issue. I can't seem to figure out where the console log output is displayed. Here's my basic code snippet: import './App.css'; function App() { ...

How can I ensure that an absolutely positioned element [created with React] snaps to the edge of its parent div when the page loads

I am currently developing a unique two-thumb slider bar component using React. Each thumb in the slider snaps to the closest discrete tick so that users can easily select values along a number line visually. One challenge I'm facing is that the thumbs ...

Tips for preserving component state during page rerenders or changes

I created a counter with context API in React, and I'm looking for a way to persist the state even when the page is changed. Is there a method to store the Counter value during page transitions, similar to session storage? My app utilizes React Router ...

Solving the NextJS white screen issue occurring on pages with getServerSideProps when directly entering the URL into the browser

Currently using Next 13, I have encountered an issue specifically during the production build phase. Although the site operates normally, when attempting to open a page by directly typing its URL into the browser, it displays either a blank page or a white ...

Tips for creating a Next.js "Link" component with an optional "href" property

I've created a custom React function using typescript for the Next.js Link component. The "href" property is necessary for the "Link" to be used anywhere, so it couldn't be utilized as a button that functions as a submit button in forms. import N ...

Achieving Vertical Alignment of Text with CSS

Can you figure out what's wrong with the placement of content outside the <footer> tag in this HTML? Also, why is the text not perfectly vertically middle-aligned? <html> <head> <style> body { ...

Invoke a method within a sibling component of the parent in a React application

My component structure is set up as follows: A serves as the parent component, with B and C acting as child components of A; making B and C siblings. Additionally, D is a child component of C. The structure looks like this: A B - function 2 C D - ...

Ways to position an element at the center using Flexbox技

Having some difficulty centering an element in my code using flexbox. It seems to work for everything else, but not here. Any suggestions or ideas? .answer { text-shadow: 0 0 2px gr; display: flex; justify-content: center; border-radius: 5px; ...

Innovative replacement for the horizontal rule element `<hr>` in HTML5

Currently, I am coding an HTML calendar using HTML5 and attempting to include a colored horizontal line. Although I have been utilizing the <hr> tag, I am facing difficulties in making most attributes function properly. Here is my desired style: &l ...

Interactive Form directly linked to SQLite3 database

Looking for assistance with converting a modal from static, fake data to dynamic data from an SQLite3 database. The goal is to display a table of existing data and allow users to add new rows by clicking a +New button. However, when trying to incorporate ...