Interactive Example · Menus
Dropdown menu with keyboard support
A menu that opens from its button with a short fade and scale, and can be used completely from the keyboard.
Written by Inspireca Design (drafted with AI assistance)Updated Not yet reviewed by an editor
Try it
Use it with a mouse, by touch or with the keyboard. The controls below show its other states.
Nothing chosen yet.
How it works
A menu is a small thing with a lot of behaviour. The animation is the easy part; the keyboard and focus rules are what make it usable.
What moves
The menu fades in and grows from 95% to full size in 150 milliseconds, from the corner nearest the button, so it appears to come out of the button. It closes the same way in reverse. The arrow in the button turns to point up while the menu is open. Use the control to open it towards the other edge.
Keep it quick
People open menus many times a day. 150 milliseconds is enough to connect the menu to its button and short enough not to be waited for. A menu that takes half a second to arrive feels slow every single time.
Behaviour to copy
- Pressing outside closes it.
- Choosing an item closes it and puts focus back on the button.
- It stays in the page while closed, invisible, so it can animate out; while closed it is marked
inert.
When not to use a menu
If there are only two actions, show two buttons. If the list is a choice of value, such as a country, use a select or a list box instead; a menu is for actions.
Accessibility notes
- Roles: the button has
aria-haspopup="menu"andaria-expanded; the list is amenuofmenuitems, following the Menu Button pattern in the WAI-ARIA Authoring Practices. - Keyboard: Enter, Space or Down opens it and focuses the first item; Up opens it at the last. Up and Down move and wrap around, Home and End jump, Escape closes it and returns focus to the button, Tab closes it and moves on.
- Result announced: the line under the demo is a status region, so the chosen action is read out.
- Items are 44 px tall.
- Reduced motion: the menu appears and disappears at once.
- Not covered here: typing a letter to jump to an item, and submenus. Add them if your menu is long.
The code
This is the source of the preview above: React with Tailwind CSS classes (dropdown-menu.tsx). Colour names such as bg-primary and the ex- animation classes come from this site’s own stylesheet; replace them with your own.
"use client";
import { useEffect, useId, useRef, useState } from "react";
import { ChevronDown } from "lucide-react";
import type { DemoProps } from "@/lib/examples/keys";
const ITEMS = ["Rename", "Duplicate", "Move to folder", "Archive"];
/**
* A menu that opens from a button with a short fade and a small scale from its corner.
* Keyboard: Enter, Space or Down opens it and focuses the first item; Up and Down move;
* Home and End jump; Escape closes it and returns focus to the button; Tab closes it.
*/
export default function DropdownMenu({ values }: DemoProps) {
const id = useId();
const [open, setOpen] = useState(false);
const [last, setLast] = useState("");
const button = useRef<HTMLButtonElement>(null);
const items = useRef<(HTMLButtonElement | null)[]>([]);
const wrapper = useRef<HTMLDivElement>(null);
const wanted = useRef(0); // which item to focus when the menu opens
const end = values.align === "end";
// Close when someone presses outside the menu.
useEffect(() => {
if (!open) return;
const outside = (e: PointerEvent) => { if (!wrapper.current?.contains(e.target as Node)) setOpen(false); };
document.addEventListener("pointerdown", outside);
return () => document.removeEventListener("pointerdown", outside);
}, [open]);
// Focus moves into the menu after it has been drawn open, never before (a hidden item cannot take focus).
useEffect(() => { if (open) items.current[wanted.current]?.focus(); }, [open]);
const openAt = (index: number) => { wanted.current = index; setOpen(true); };
const close = (returnFocus: boolean) => { setOpen(false); if (returnFocus) button.current?.focus(); };
const focusItem = (index: number) => items.current[(index + ITEMS.length) % ITEMS.length]?.focus();
const onMenuKeyDown = (e: React.KeyboardEvent) => {
const at = items.current.indexOf(document.activeElement as HTMLButtonElement);
if (e.key === "ArrowDown") { e.preventDefault(); focusItem(at + 1); }
else if (e.key === "ArrowUp") { e.preventDefault(); focusItem(at - 1); }
else if (e.key === "Home") { e.preventDefault(); focusItem(0); }
else if (e.key === "End") { e.preventDefault(); focusItem(ITEMS.length - 1); }
else if (e.key === "Escape") { e.preventDefault(); close(true); }
else if (e.key === "Tab") close(false);
};
return (
<div className="flex h-56 w-full max-w-xs flex-col items-center">
<div ref={wrapper} className="relative">
<button ref={button} type="button" id={`${id}-button`} aria-haspopup="menu" aria-expanded={open} aria-controls={`${id}-menu`}
onClick={() => (open ? close(false) : openAt(0))}
onKeyDown={(e) => { if (e.key === "ArrowDown") { e.preventDefault(); openAt(0); } else if (e.key === "ArrowUp") { e.preventDefault(); openAt(ITEMS.length - 1); } }}
className="inline-flex h-11 items-center gap-2 rounded-[10px] border border-border-strong bg-background px-4 text-sm font-medium outline-none hover:bg-surface focus-visible:ring-2 focus-visible:ring-foreground">
Actions <ChevronDown aria-hidden className={`size-4 transition-transform duration-150 motion-reduce:transition-none ${open ? "rotate-180" : ""}`} />
</button>
{/* Always in the page so it can animate out; invisible and inert while closed. */}
<div id={`${id}-menu`} role="menu" aria-labelledby={`${id}-button`} inert={!open} onKeyDown={onMenuKeyDown}
className={`absolute top-full z-10 mt-2 w-48 rounded-xl border border-border bg-background p-1 shadow-[0_12px_32px_rgb(0_0_0/0.12)] duration-150 ease-out motion-reduce:transition-none ${end ? "right-0 origin-top-right" : "left-0 origin-top-left"} ${
// Opening: visible at once, so focus can move in. Closing: stay visible until the fade has finished.
open ? "visible scale-100 opacity-100 transition-[opacity,transform]" : "invisible scale-95 opacity-0 transition-[opacity,transform,visibility]"}`}>
{ITEMS.map((label, i) => (
<button key={label} ref={(el) => { items.current[i] = el; }} type="button" role="menuitem" tabIndex={-1}
onClick={() => { setLast(label); close(true); }}
className="flex h-11 w-full items-center rounded-lg px-3 text-left text-sm outline-none hover:bg-surface focus-visible:bg-surface-strong">
{label}
</button>
))}
</div>
</div>
<p role="status" className="mt-auto text-sm text-muted-foreground">{last ? `You chose “${last}”.` : "Nothing chosen yet."}</p>
</div>
);
}
See it in real apps
Still screenshots from the Inspireca Design library of the kinds of screen where this interaction is used. A screenshot cannot show the motion itself.