cssreactjstypescriptnext.jsclassname

Tailwindcss + Nextjs problems with class + variables


Good afternoon, I need help with a big problem I'm having with tailwindcss + nextjs...

So the problem is when it comes to setting the classes, I need to use a variable, the class is set in the css, but the tailwind is not converting the class into a style.

I need it to be like this:

enter image description here

I already tried to set the class as constant, I tried to set the constant both inside the component and in getstaticprops, and none of them worked. I've tried to set a class within the css itself and it didn't work either.


Solution

  • Tailwind uses regex to find class names, and because of this they need to exist as unbroken strings in your source code. A consequence of this is you cannot use string interpolation the way you're trying to do, as Tailwind will not be able to find the class name.

    What you can do instead is map your props to static class names:

    const Component = ({pokemon}) => {
      const pokemonBgVariants = {
        pikachu: 'bg-pokemontype-pikachu',
        bulbasaur: 'bg-pokemontype-bulbasaur',
        // ...
      }
    
      return (
        <div className=`[...other classes] ${pokemonBgVariants[pokemon.types[0].type.name]}`></div>
      )
    }