Ariakit
/

Animated Select

Animating Select using CSS transitions in React. The component waits for the transition to finish before completely hiding the popover.

Open preview in a new tab
Favorite fruit
Edit withViteNext.js
import "./style.css";
import * as Ariakit from "@ariakit/react";
export default function Example() {
return (
<div className="wrapper">
<Ariakit.SelectLabel className="label">
Favorite fruit
<Ariakit.Select className="button" />
gutter={4}
className="popover"
>
<Ariakit.SelectItem className="select-item" value="Apple" />
<Ariakit.SelectItem className="select-item" value="Banana" />
<Ariakit.SelectItem className="select-item" value="Grape" />
<Ariakit.SelectItem className="select-item" value="Orange" />
</div>
);
}

Components

Setting the animated prop

When animating Select with CSS transitions, the animated prop must be set to true on the SelectProvider component. This instructs Ariakit to assign the data-enter and data-leave attributes and wait for the transition to finish before hiding or unmounting the SelectPopover component:

Conditional mouting

While not mandatory, in this example, we're using the mounted state to conditionally render the SelectPopover component:

const [mounted, setMounted] = useState(open);
{mounted && <SelectPopover />}

The mounted state derives from the open state. They usually coincide. However, when the animated prop is set to true, these two values might differ. The mounted state remains true while SelectPopover is animating out, which allows it to finish its transition before it is hidden or unmounted.

In short, the mounted state represents the following logic:

const mounted = open || animating;

Styling the animation

For more information on styling with Ariakit, refer to the Styling guide.

Use the data-enter and data-leave attributes to animate the SelectPopover component using CSS transitions:

.popover {
opacity: 0;
transition: opacity 150ms;
}
.popover[data-enter] {
opacity: 1;
}

Follow updates

Join 1,000+ subscribers and receive monthly updates with the latest improvements on Examples.

Read latest issue

No Spam. Unsubscribe at any time.