1

So I have a code in ReactJS using Tailwind CSS that goes hover:bg-${color}-200 bg-${color}-100 which works fine. However, when I change it to hover:bg-${color}-300 bg-${color}-200, the bg-${color}-200 part works but the hover part doesn't. I have tested hover:bg-${color}-400 and it works just fine.

Why don't the hover work when it's 300? Is there anyway that I can make it work?

I have also tried 50, 500, 700, 800, 900 and 950 and they don't work as well. What works are 200, 400 and 600. Is there a reason for this?

I'm not sure if this additional information can help - I've placed the code in a tr tag.

1

1 Answer 1

2

As per the documentation:

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

Don’t construct class names dynamically

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:

Always use complete class names

<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

hover:bg-${color}-200, bg-${color}-100, bg-${color}-200 and hover:bg-${color}-400 work by coincidence since the resulting class appear as unbroken strings in other code scanned by Tailwind.

To resolve your problem, you could consider using full class names in definitions, like:

const color = 'bg-red-200 hover:bg-red-300';

<div className={color}>

Or you could consider adding the possible classes to the safelist:

/** @type {import('tailwindcss').Config} */
module.exports = {
  // …
  safelist: [
    { pattern: /^bg-(red|green|blue)-200$/ },
    {
      pattern: /^bg-(red|green|blue)-300$/,
      variants: ['hover'],
    },
  ],
  // …
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.