0

I am using a package called

react-type-animation

for a typewriter text effect with react and tailwind css. But when I add dynamic class to the TypeAnimation component, it does not work. Here is the code that I have tried:

<TypeAnimation sequence={[
              "TEXT1",
              2000,
              "TEXT2",
              2000,
              "TEXT3",
              2000,
            ]}
              speed={50}
              className={`text-${theme}-500`}
              wrapper="span"
              repeat={Infinity}
            />

But when i use static class like text-red-500, it works fine. Is there any way to use dynamic class to the TypeAnimation component?

Shakil Ahmed
  • 39
  • 1
  • 5

1 Answers1

0

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:

  • Have the entire class in the variable you pass to className like

    const textColor = '';
    if (theme == 'red') {
      textColor = 'text-red-500';
    }
    
    // …
    
    <TypeAnimation … className={textColor} />
    
  • Use the style attribute for truly dynamic colors, if theme can be converted to a valid CSS color value (or you could get the color from Tailwind):

    <TypeAnimation … style={{ color: theme }} />;
    
  • safelist the classes, if you have a limited number of known colors:

    module.exports = {
      safelist: [
        'text-red-500',
        // …
      ],
      // …
    ];
    
Wongjn
  • 8,544
  • 2
  • 8
  • 24
  • Thanks. I added the classes to the safelist and now they are working fine. – Shakil Ahmed May 27 '23 at 10:07
  • I can see the docs does not recommendes to use safelist. So I went with the if else method. I generated a whole class name and then added the className to the TypeAnimation component. – Shakil Ahmed May 27 '23 at 10:22