Home > Back-end >  tailwind css custom class passed as props is not overriding the already applied class
tailwind css custom class passed as props is not overriding the already applied class

Time:07-07

I am using tailwind classes and below is my code. some people suggested to use classNames so used that as well, so similar code in both the newer and older format

const backgroundColor = disabled ? "bg-secondary-500" : "bg-green-700";
className={classNames(
        "w-20 my-2 p-2 text-white rounded capitalize hover:ease-in hover:scale-110 hover:duration-200",
        customClass,
        backgroundColor,
        { "pointer-events-none": true }
      )}
 className={`w-20 my-2 p-2 text-white bg-green-700 rounded capitalize 
             hover:ease-in hover:scale-110 hover:duration-200 
             ${disabled ? "pointer-events-none bg-secondary-500" : ""} 
             ${customClass}`}

so in my customClass I have "w-60". but "w-20" is only getting applied. even it is happening for "bg-green-700" and I wanted it to be "bg-secondary-500" for disabled: true

so my disabled is coming as true and pointer-event-none is getting applied but secondary class is overridden by green class

I checked the DOM and both the bg class and both the width classes are available in the below order

<button >View Docs
</button>

so if anyone has any idea this is happening, please help

CodePudding user response:

For merging Tailwind classes use https://github.com/dcastil/tailwind-merge instead of classNames

import { twMerge } from 'tailwind-merge'

// ...

className={twMerge(
  "w-20 my-2 p-2 text-white bg-green-700 rounded capitalize hover:ease-in hover:scale-110 hover:duration-200",
  disabled && "pointer-events-none bg-secondary-500",
  customClass
)}

CodePudding user response:

Here if I understood correctly , you want bg-secondary-500 when button is disabled. This can be done by this

className={`w-20 my-2 p-2 text-white rounded capitalize
             hover:ease-in hover:scale-110 hover:duration-200
             ${disabled ? "pointer-events-none bg-secondary-500" : "bg-green-500 pointer-events-auto"}
             `}

However you need to add any condtion if you want to change from w-20 to w-60. Else simply use w-60.

  • Related