1

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.

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
ibij
  • 41
  • 1
  • 2
  • Also answered here: https://stackoverflow.com/questions/75664539/tailwind-css-class-precedence-is-not-respected/75666082#75666082 – Ed Lucas May 26 '23 at 20:16

1 Answers1

1

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,
  })}
>
Wongjn
  • 8,544
  • 2
  • 8
  • 24