Tailwind custom color is not working in classNames

1k views Asked by At

Set up tailwind.config.js as follows to specify custom colours.

theme: {
    extend: {
      colors: {
        "text-gray": "#747474",   Works on its own.
        "text-black": "#212121",  Works on its own.
     "text-black2": "#212121", dummy color
      },
    },
  },

text-gray and text-black work fine on their own, but do not work if you take a boolean value such as isSelected and try to change the colour dynamically using classnames.

    import classNames from "classnames";
    
    interface PlayerSelectionProps {
      isSelected?: boolean;
    }
    
    export function PlayerSelection({
      isSelected = false,
    }: PlayerSelectionProps): JSX.Element {
      return (
        <p
          className={classNames("mb-2 mt-4 text-text-gray md:text-lg", {
            "text-text-black": isSelected,   // With text-black-2 it works.
          })}
        >
          sample text
        </p>
      );
    }

Why is text-text-gray applied when using a certain component like this? I looked at some reference links, but nothing gave me much of a clue.

2

There are 2 answers

0
Wongjn On

The problem here is that when isSelected is truthy, you are applying two classes with the same variant context that apply the same property and thus conflict. The style that wins out is the one that is defined latest in the CSS source order when they have the same specificity:

.text-red {
  color: red;
}

.text-green {
  color: green;
}
<div class="text-red text-green">Foo<div>
<div class="text-green text-red">Foo<div>

So, in your situation, consider applying only one of text-text-gray or text-text-black at any one time:

<p
  className={classNames("mb-2 mt-4 md:text-lg", {
    "text-text-black": isSelected,
    "text-text-gray": !isSelected,
  })}
>
0
shwet upadhyay On

This is how I solved it:

  1. Create an object or objects with attributes you want to change with props.

    let colorClass = {
         blue: "bg-blue-400", orange: "bg-orange-600" 
    };
    
  2. Put all the fixed classes as first argument in classNames and all the prop dependent ones after it.

    className={classNames('hover:cursor-pointer px-5', colorClass[color])}
    

    like colorClass we can have as many props dependent as we want. and it looks readable.