Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried to change it with this line of code it but it doesn't work

const [click, setClick] = useState(false);

const closeNav = () => {
  setClick(!click);
};

const openNav = () => {
  setClick(!click);
};

<div
  className=" absolute inset-0 ${click ? translate-x-0 : -translate-x-full } 
        transform  z-400 h-screen w-1/4 bg-blue-300 "
>
  <XIcon onClick={closeNav} className=" absolute h-8 w-8 right-0 " />
</div>;
like image 525
vinender singh Avatar asked Jun 17 '21 13:06

vinender singh


1 Answers

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:

  • React.js conditionally applying class names
  • How to dynamically add a class to manual class names?
  • Correct way to handle conditional styling in React
  • Embedding Expressions in JSX
  • Template literals - MDN
  • Optimizing for Production - Writing purgeable HTML - Tailwind CSS
like image 157
brc-dd Avatar answered Sep 27 '22 17:09

brc-dd