13

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>;
MarioG8
  • 3,423
  • 4
  • 6
  • 20
vinender singh
  • 199
  • 1
  • 7

1 Answers1

20

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:

brc-dd
  • 6,933
  • 3
  • 26
  • 51
  • 1
    I was puzzled by the bug which was caused by template literal concatanations, thank you! Didn't know it was also warned against in docs: https://tailwindcss.com/docs/content-configuration#class-detection-in-depth – kuzdogan Jan 06 '22 at 15:15
  • 1
    You can safelist classes if you need to interpolate/concatenate template literals. https://tailwindcss.com/docs/content-configuration#class-detection-in-depth – J. Adam Connor Feb 02 '22 at 06:29
  • thank you so much, I was adding class names from props like `bg-${props.color}` and couldn't get the desired result. Above answer helped me. – Ashutosh Dash Apr 19 '22 at 05:58