useTransition
Hook used to animate the appearance or the disappearance of a component.
Usage
useTransition
generates data-* props which you can use as selectors in CSS. It will also ensure that the element will only get hidden when the transition has ended.
Use the [data-enter]
and [data-leave]
selectors to style both enter and leave animations. data-enter is added shortly after the element is shown so there's an interval for the browser to process the initial styles and understand this as a transition.
This example is voluntarily simple and don't use Ariakit Disclosure. For production ready code, it should use it.
Content
import { useState } from "react";
import { Button } from "swash/Button";
import { useTransition } from "swash/motion/Transition";
import { cn } from "swash/utils/classNames";
export const Example = () => {
const [visible, setVisible] = useState(true);
const {
style,
"data-enter": dataEnter,
"data-leave": dataLeave,
hidden,
} = useTransition(visible);
return (
<>
<Button type="button" onClick={() => setVisible((visible) => !visible)}>
Toggle
</Button>
<div
className={cn(
"opacity-0",
"data-[enter]:translate-y-0 data-[enter]:opacity-100 data-[enter]:transition-opacity data-[enter]:duration-300 data-[enter]:ease-in",
"data-[leave]:transition-opacity data-[leave]:duration-200 data-[leave]:ease-out",
)}
style={style}
hidden={hidden}
data-enter={dataEnter}
data-leave={dataLeave}
>
Content
</div>
</>
);
};