How to use dynamic className with TypeAnimation component?

96 views Asked by At

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?

1

There are 1 answers

2
Wongjn On

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',
        // …
      ],
      // …
    ];