26

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
  • 5,122
  • 4
  • 13
  • 29
vinender singh
  • 339
  • 1
  • 3
  • 8

2 Answers2

41

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
  • 10,788
  • 3
  • 47
  • 67
  • 4
    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
  • 2
    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
  • 1
    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
0
 const bgClass: any = {
gray: " bg-gray-300",
red: " bg-red-300",
orange: " bg-orange-300",
yellow: " bg-yellow-300",
green: " bg-green-300",
teal: " bg-teal-300",
blue: " bg-blue-300",
indigo: " bg-indigo-300",
purple: " bg-purple-300",
pink: " bg-pink-300 ",

}

const convertLabelToBg = (label: string, baseClass: string): string => {
    let className: string = baseClass;
    if (label) {
        className += bgClass[label];
    }
    return className;
}

It worked for me. I have followed the documentation.

https://tailwindcss.com/docs/content-configuration#dynamic-class-names