I have build a sliding submenu with React, Typescript and Tailwind.
The related submenu is showing using React useState
hook.
See the working code sandbox here.
Why is my close css animation not working data-[state=closed]:animate-[submenu-hide_300ms]
? The open animation data-[state=open]:animate-[submenu-show_300ms]
works.
How to fix this?
Update:
Instead of doing:
{clickedItem === item && (
<ul
data-state={dataSate}
className="fixed top-0 flex h-svh w-[300px] flex-col bg-red-300 ease-in data-[state=closed]:animate-[submenu-hide_300ms] data-[state=open]:animate-[submenu-show_300ms]"
>
<li>
<button
onClick={() => setClickedItem(null)}
type="button"
className="flex items-center p-2"
>
<span className="mr-10">Back</span>
<span className="font-bold">{item.title}</span>
</button>
</li>
{item.items?.map((item) => (
<li key={item.url}>
{item.items && item.items.length > 0 ? (
<button
onClick={() => handleClick(item)}
className="flex w-full justify-between p-2"
type="button"
>
{item.title}
<span>[+]</span>
</button>
) : (
<a href={item.url} className="p-2">
{item.title}
</a>
)}
</li>
))}
</ul>
)}
I tried the following (show/hide it with css instead of React useState), but the animation is still not working when hiding the element?:
<ul
data-state={dataSate}
className={`${clickedItem === item ? 'left-0 animate-[submenu-show_300ms]' : 'left-[-375px] animate-[submenu-hide_300ms] overflow-hidden'} fixed top-0 flex h-svh w-[375px] flex-col bg-red-300 ease-in`}
>
<li>
<button
onClick={() => setClickedItem(null)}
type="button"
className="flex items-center p-2"
>
<span className="mr-10">Back</span>
<span className="font-bold">{item.title}</span>
</button>
</li>
{item.items?.map((item) => (
<li key={item.url}>
{item.items && item.items.length > 0 ? (
<button
onClick={() => handleClick(item)}
className="flex w-full justify-between p-2"
type="button"
>
{item.title}
<span>[+]</span>
</button>
) : (
<a href={item.url} className="p-2">
{item.title}
</a>
)}
</li>
))}
</ul>
2
You will need to fix the css, hide should transform from 300px to 0.
@keyframes submenu-hide {
from {
opacity: 1;
transform: translateX(300px);
}
to {
opacity: 0;
transform: translateX(0);
}
}
See working example: https://codesandbox.io/p/devbox/slide-menu-transition-p4t8mm