ReactMedium

Dropdown menu

A dropdown menu toggles a list of actions from a trigger button and must close when clicking outside, pressing Escape, or choosing an item. Implement open state, an outside-click listener (pointerdown on document that ignores clicks inside the menu), keyboard support (arrow keys to move between items, Escape to close and return focus), and ARIA attributes (aria-haspopup, aria-expanded, role="menu" and role="menuitem").

Requirements

  1. Trigger button toggles the menu.
  2. Close on outside click, Escape, item selection and when focus leaves.
  3. Keyboard: Down/Up arrows move through items, Home/End, Enter activates; focus returns to the trigger on close.
  4. Positioning that avoids overflow (flip above when near the bottom).

Implementation notes

  • Use a ref on the wrapper and check wrapper.contains(event.target) in a document pointerdown listener, added only while open and removed in cleanup.
  • Manage item focus with refs and roving tabIndex.
  • Use useId to link the trigger and menu.

Modern platform features

  • Popover API: <button popovertarget="menu"> and <div id="menu" popover> give top-layer rendering, light dismiss (outside click and Escape) and no z-index problems, with no JavaScript.
  • CSS anchor positioning places the popover relative to the button.

Libraries

Radix Dropdown Menu, React Aria Menu, Headless UI Menu and Floating UI handle typeahead, submenus, collision detection and screen reader details.

Code example

tsx
1import { useEffect, useId, useRef, useState } from "react";
2
3const actions = ["Edit", "Duplicate", "Archive", "Delete"];
4
5export function ActionsMenu({ onSelect }: { onSelect: (a: string) => void }) {
6 const [open, setOpen] = useState(false);
7 const wrapperRef = useRef<HTMLDivElement>(null);
8 const triggerRef = useRef<HTMLButtonElement>(null);
9 const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
10 const menuId = useId();
11
12 useEffect(() => {
13 if (!open) return;
14 itemRefs.current[0]?.focus();
15 const onPointerDown = (e: PointerEvent) => {
16 if (!wrapperRef.current?.contains(e.target as Node)) setOpen(false); // outside click
17 };
18 document.addEventListener("pointerdown", onPointerDown);
19 return () => document.removeEventListener("pointerdown", onPointerDown);
20 }, [open]);
21
22 function close() {
23 setOpen(false);
24 triggerRef.current?.focus(); // return focus
25 }
26
27 function onKeyDown(e: React.KeyboardEvent, i: number) {
28 const n = actions.length;
29 if (e.key === "Escape") return close();
30 const next = e.key === "ArrowDown" ? (i + 1) % n : e.key === "ArrowUp" ? (i - 1 + n) % n : e.key === "Home" ? 0 : e.key === "End" ? n - 1 : -1;
31 if (next >= 0) { e.preventDefault(); itemRefs.current[next]?.focus(); }
32 }
33
34 return (
35 <div ref={wrapperRef} style={{ position: "relative", display: "inline-block" }}>
36 <button ref={triggerRef} aria-haspopup="menu" aria-expanded={open} aria-controls={menuId} onClick={() => setOpen((o) => !o)}>Actions ▾</button>
37 {open && (
38 <div id={menuId} role="menu" style={{ position: "absolute", top: "100%", left: 0, background: "white", boxShadow: "0 4px 12px #0002" }}>
39 {actions.map((a, i) => (
40 <button key={a} ref={(el) => { itemRefs.current[i] = el; }} role="menuitem" tabIndex={-1}
41 onKeyDown={(e) => onKeyDown(e, i)} onClick={() => { onSelect(a); close(); }} style={{ display: "block", width: "100%" }}>
42 {a}
43 </button>
44 ))}
45 </div>
46 )}
47 </div>
48 );
49}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app