htmlcssreactjstailwind-csstransition

Tailwind transition stop working in React


I use this isVisible to trigger the transition

    useEffect(() => {
        const timer = setTimeout(() => {
            setIsVisible(true);
        }, 500);

        return () => clearTimeout(timer);
    },[]);
<img src={background} alt="background" className={`
                absolute top-[20%] -left-[20%] transform z-0
                transition duration-[2s] ease-in-out opacity-${isVisible ? 50 : 0} 
              scale-[${isVisible ? "180%" : "100%"}]`}/>

It works well at the beginning, but suddenly stops working properly. The opacity change has the transition, but instead of changing to the desired value, it can only change from 0% to 100%, the scale, and translate are not working at all. What's the problem with the code?


Solution

  • In your current setup, the variables isVisible are being inserted into the string but not being evaluated as JavaScript expressions. This is why you're finding the opacity always turns to either 0% or 100%, and the scaling doesn't work.

    This is how you can fix it:

    useEffect(() => {
        const timer = setTimeout(() => {
            setIsVisible(true);
        }, 500);
    
        return () => clearTimeout(timer);
    },[]);
    <img src={background} alt="background" className={`
                absolute top-20% -left-20% transform z-0
                transition duration-2000 ease-in-out ${isVisible ? 'opacity-50' : 'opacity-0'}
                ${isVisible ? 'scale-180' : 'scale-100'}`}/>