How to use template literals in tailwindcss to change classes dynamically?

Do it like this:

<div className={`absolute inset-0 ${click ? 'translate-x-0' : '-translate-x-full'} transform z-400 h-screen w-1/4 bg-blue-300`}></div>

// Alternatively (without template literals):
<div className={'absolute inset-0 ' + (click ? 'translate-x-0' : '-translate-x-full') + ' transform z-400 h-screen w-1/4 bg-blue-300'}></div>

Just keep in mind not to use string concatenation to create class names, like this:

<div className={`text-${error ? 'red' : 'green'}-600`}></div>

Instead you can select complete class name:

<div className={`${error ? 'text-red-600' : 'text-green-600'}`}></div>

// following is also valid if you don't need to concat the classnames
<div className={error ? 'text-red-600' : 'text-green-600'}></div>

As long as a class name appears in your template in its entirety, Tailwind will not remove it from production build.


There are some more options available for you like using a library like classnames or clsx, or maybe Tailwind specific solutions like twin.macro, twind, xwind.

Further Reading:

Leave a Comment