TailwindCSS class names do not take precedence over one another

I am working on creating a Button component in ReactJS that can be styled using props such as primary, rounded, and outline. To apply these styles, I use the className function from the "classnames" library.

import className from 'classnames'

interface ButtonProps {
    children: any // Elements placed within the Button
    outline?: boolean // Adds an outline to the Button, removing background color and changing font color
    rounded?: boolean // Adds border radius to the Button
    primary?: boolean // Sets a blue background color for the Button
    [key: string]: any // Additional props like event handlers
}

function Button({
    children,
    outline,
    rounded,
    primary,
    ...rest
}: ButtonProps) {

const classNames = 
    className(
        'flex items-center select-none px-3 py-0.5 border border-2 font-medium',
        {
            'text-white bg-blue-600 border-blue-600': primary,
            'rounded-lg': rounded,
            'text-blue-500 bg-transparent': outline && primary,
        },
        rest.className
    )

return (
        <button {...rest} className={classNames}>
            {children}
        </button>
    )
}

When I only set the primary prop, the Button looks like this:

https://i.sstatic.net/NfFc2.jpg

The classnames in the browser inspector show

flex items-center select-none px-3 py-0.5 border border-2 font-medium text-white bg-blue-600 border-blue-600
, which is correct. However, when I add both the outline and primary props, the Button appears differently:

https://i.sstatic.net/SIaTC.jpg

The classnames change to

flex items-center select-none px-3 py-0.5 border border-2 font-medium text-white bg-blue-600 border-blue-600 text-blue-500 bg-transparent

As seen, bg-transparent and text-blue-500 override bg-blue-600 and text-white. It seems that bg-blue-600 is overridden by bg-transparent, but text-white is not overridden by text-blue-500.

This issue can be observed in the CSS styles section of the Developer tools: https://i.sstatic.net/ImuM7.png

Why does this happen and how can I resolve this problem?

Thank you!

Answer №1

Avoid using multiple class names that have the same effect on an element with the same style at once. If you try to use both outline and primary, you may experience conflicting styles like text-white vs text-blue-600 and bg-blue-600 vs bg-transparent. It's recommended to apply only one of these classes at a time, for example:

const classNames = 
    className(
        'flex items-center select-none px-3 py-0.5 border border-2 font-medium',
        {
            'border-blue-600': primary,
            'text-white bg-blue-600': primary && !outline,
            'rounded-lg': rounded,
            'text-blue-500 bg-transparent': outline && primary,
        },
        rest.className
    )

Answer №2

If you want to achieve your desired outcome, make sure to use the unique "dedupe" version available. This specific classNames version has the ability to overwrite any existing classes. To include this version in your project, simply append "/dedupe" to your import statement :

import classNames from "classnames/dedupe";

https://github.com/JedWatson/classnames#alternate-dedupe-version

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

Can you develop with React using JSX without relying on a node server and instead utilizing create-react-app?

I find myself in a difficult situation - I am relatively new to React and I proposed to convert a project from pure JavaScript to ReactJS at my workplace. The catch is that I can't use a node server for this project. So far, I have been coding React w ...

Display Button and Div when Event occurs in Asp.net core using Razor Pages

I am currently working on a project that involves two dropdown menus: one for Categories and the other for SubCategories. Within a partial view named _CreateProject, I have set up an html form to facilitate the creation of new projects. My goal is to have ...

Scrolling with jQuery just got a sleek upgrade with our new

Can anyone suggest a jQuery scrollbar that resembles the clean black bar found on the iPhone? I need a simple design without visible up or down buttons. Many scripts I came across offer more features than necessary for my project. My div element has a fi ...

The PrimeNg confirmDialog is updating my navbar with some modifications

Despite my navbar working well and being fully responsive, I encountered an issue where opening a confirm dialog in the background caused the navbar width to expand to 800px even though the screen width was 1480px, creating empty space on the right side, a ...

Children on the route are being overlooked

Hi everyone, I'm new to React-Router and currently working on a simple project. I have three components in my app: header, sidebar, and index. While the header and sidebar render fine in the browser, the index component is not displaying properly. I ...

Effortless Route Loading in React Using Typescript's AsyncComponent for Dynamic Loading

I have been experimenting with lazy loading routes in React by following the example provided in the documentation for implementing the AsyncComponent class. The tutorial I referenced can be found here. Below is the asyncComponent function written in ES6 f ...

Issue with Bootstrap CSS not rendering properly in Chrome and Firefox

After creating a simple "Hello World" web page and including Bootstrap CSS from a CDN, I noticed that it's only working properly in Microsoft Edge. Both Google Chrome and Mozilla Firefox are not displaying the correct output. I would greatly apprecia ...

Retrieve the desired placeholder text color by utilizing the capabilities of the Selenium WebDriver

https://i.sstatic.net/g52uN.pngLooking for guidance on how to verify the color of placeholder text in an input element using Selenium and Java. In my test scenario, I have an HTML structure like this: <div class="pe-input"> <label for="in ...

Editable span Option

One of my skills includes creating a dynamic contenteditable span within text that can expand and contract, as well as wrap around multiple lines without taking up the entire width: div { width: 100px; background: #f00; padding: 5px; } span { bo ...

Is it necessary for the React generic type prop to be an extension of another type

I have recently started using TypeScript and I am facing a confusion regarding passing generic types into my higher-order component (HOC). My objective is to pass the component props as a generic type in order to have the Component with those specific type ...

The optimal placement for the business logic of a Chrome extension

As I dive into building my inaugural Chrome extension, a pressing inquiry arises regarding the optimal placement of the main logic and API calls. Given that I utilize React for the popup interface, one potential approach is housing all of the logic within ...

Guide on how to upload a file in React JS while sending Json Data simultaneously

I'm working on a React.js application where I need to upload a file from React.js to Node.js using Multer as multipart-formdata. It's working fine for our requirements. However, I'm stuck on how to send the JSON data along with the uploaded ...

Tips for successfully passing import as props arguments in React JS

I am using react-lotties and would like to add different animations to multiple divs by just changing the URL of the lotties As a beginner in React, please be kind :) This is my code snippet : My Lotties Component : import React, { Component } f ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

"amCharts Version 4 introduces a new feature allowing for the month format to be displayed on the Date

When setting up my XYChart, I am facing an issue with the x-Axis labels. I want to display the twelve months from Jan to Dec, but in the image provided, the first month is also showing the Year (yyyy) along with it. let dateAxis = chart.xAxes.push(new ...

Unable to see Primereact styles reflected on components

After some investigation, I've pinpointed the issue to be related to preflight from tailwind. Upon reviewing the documentation, I came across this helpful information: CSS Layer It seems that using Tailwind CSS with styled or unstyled modes of PrimeR ...

Are there any alternatives to using <HR/> for creating lines in Bootstrap 3?

While working on my page design using Bootstrap 3, I noticed that the `` tag has too much margin. This is causing it to not fit well with the overall compact look of my page. Do you have any alternative options for drawing a line in Bootstrap 3 that woul ...

Need to update various form fields at once with jquery?

There is a form with fields for firstname, lastname, email, country, along with edit icon and submit/cancel buttons. When the user clicks on the edit icon in the top right corner, all values will be displayed in textboxes and the country will be shown in ...

Retrieve the currently logged-in user whenever the component is rendered using React's Context API

For my small React project, I am utilizing ContextAPI. Whenever I hit the /login endpoint, I store the user's token using an HttpOnly Cookie. Below is the code for UserContext.js, which encapsulates all components (children) within App.js import axio ...

What are the steps to connect to a local network website with Internet Explorer 11?

I'm currently facing an issue with accessing a basic react application within my local network using IE on a Windows system. The site operates smoothly on Chrome, but fails to load on IE. Upon entering the URL in IE, I am presented with a blank screen ...