shadowoff09
shadowoff09

Reputation: 33

Unable to render Tailwind CSS properties dynamically

I am trying to render Tailwind CSS properties dynamically and the class is being applied in the browser inspector but the color is not changing.

I have a function that takes as input an rarity (tier) and returns the Tailwind CSS property that shows the color of that tier:

export function checkRarity(tier: string) {
  const rarityLookup = new Map([
    ["COMMON", "text-rarity-common"],
    ["UNCOMMON", "text-rarity-uncommon"],
    ["RARE", "text-rarity-rare"],
    ["EPIC", "text-rarity-epic"],
    ["LEGENDARY", "text-rarity-legendary"],
    ["MYTHIC", "text-rarity-mythic"],
    ["DIVINE", "text-rarity-divine"],
    ["SPECIAL", "text-rarity-special"],
    ["VERY_SPECIAL", "text-rarity-very-special"],
  ]);

  return rarityLookup.get(tier) || "bg-gray-400";
}

Then I am trying merge the manually typed property and and the dynamic one using twMerge and clsx as I seen at dynamically-build-classnames-in-tailwindcss.

This is the function:

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

And here I am trying to call the function to merge the Tailwind classes:

const textColor = cn("text-2xl", checkRarity(auction.tier));

Then here I am applying the className:

<h2 className={textColor}>
            {text}        
 </h2>

I have tried the following things to fix the issue:

But for some reason the only Tailwind class that works is text-rarity-legendary.

Upvotes: 1

Views: 231

Answers (1)

docker compose
docker compose

Reputation: 868

Tailwind doesn’t include any sort of client-side runtime, so class names need to be statically extractable at build-time, and can’t depend on any sort of arbitrary dynamic values that change on the client.

You can use inline styles for these situations:

export function checkRarity(tier: string) {
   const rarityLookup = new Map([
      ['COMMON', '#fff'],
      //...
   ]);

   return rarityLookup.get(tier) || '#fff';
}

Upvotes: 1

Related Questions