Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TailwindCSS animations on conditionally rendered components in React

If I am conditionally rendering a component depending on some state, how can I animate its transition between its open and closed states in React with TailwindCSS?

{successMessage && (
              <div className="flex transition-all ease-in-out duration-300 bg-gray-200 w-44 items-center justify-between px-2 rounded">
                <p>Added to watchlist!</p>
                <button onClick={() => setSuccessMessage(false)}>X</button>
              </div>
            )}

This code half works but there is no animation or transition period to it. How can I fix this?

like image 296
Eric Pezzulo Avatar asked Oct 20 '25 18:10

Eric Pezzulo


2 Answers

Two states works great. With first one add/remove "hidden" class. And with second one change opacity/height/translate or what you need for animation.

Use useEffect and setTimeout with 0 delay for changing the state of secondState. like below:

useEffect(() => {
setTimeout(() => {
  setSecondState(firstState)
}, 0) }, [firstState])

<div className={`${firstState ? "hidden" : ""} ${secondState ? "opacity-100" : "opacity-0"}`} />
like image 187
Sina Hosseini Avatar answered Oct 22 '25 07:10

Sina Hosseini


The "official" solution is to use Headless UI's Transition component.

Headless UI is created and maintained by the same authors of Tailwind CSS.

like image 21
Camilo Avatar answered Oct 22 '25 08:10

Camilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!