1

Let say the primary color of every button is bg-gray-600 and i wanted to change it to bg-indigo-600. I tried using the template literals but it has no effect on UI.

const mycomponent = () => {
  const [color, setColor] = useState('blue');

  return (
    <>
      <button
        onClick={() => {
          setColor('gray');
        }}
      >
        Change color to gray
      </button>{' '}
      <div className={`bg-${color}-600 p-2`}> Hello world </div>{' '}
    </>
  );
};

The above code did changed the class but the color didnt changed, however when apply the class bg-gray-600 as it is without the template strings , then it works, what am i missing?

1
  • Yup it does answer my question. Commented Jul 30, 2023 at 18:21

1 Answer 1

1

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>

You could consider:

  • Using full class names like:

    const mycomponent = () => {
      const [color, setColor] = useState('bg-blue-600');
    
      return (
        <>
          <button
            onClick={() => {
              setColor('bg-gray-600');
            }}
          >
            Change color to gray
          </button>{' '}
          <div className={`${color} p-2`}> Hello world </div>{' '}
        </>
      );
    };
    
  • Adding the class names to safelist:

    module.exports = {
      …
      safelist: [
        { pattern: /^bg-(red|gray|blue)-600$/ },
      ],
      …
    }
    
Sign up to request clarification or add additional context in comments.

1 Comment

It worked ! by adding class as <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>,. Thanks for the detailed explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.