Search code examples
csssasstailwind-csstailwind-uitailwind-3

tailwind css custom class passed as props is not overriding the already applied class


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 class="w-20 my-2 p-2 text-white bg-green-700 rounded capitalize 
    hover:ease-in hover:scale-110 hover:duration-200 w-60 
    bg-secondary-500 pointer-events-none">View Docs
</button>

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


Solution

  • 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
    )}