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?
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"}`} />
The "official" solution is to use Headless UI's Transition
component.
Headless UI is created and maintained by the same authors of Tailwind CSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With