How to Build a Nested Dropdown Menu in React
ReactAccessibility,Keyboard Navigation,Playwright,Pointer Events,TypeScript
A nested dropdown menu is written as tree-shaped data, where the contents of the menu are held in children, and it is built by calling the same function again inside the function that renders the menu (recursion). Which submenu is open is held in a single array of the ids of the open parent items, listed from the top level down. This way, only one submenu can be open at each level, and "going back up one level" just means removing the last element of the array.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and used Playwright to send pointer movements, clicks, and key presses to Chromium to verify the behavior. When the whole app was wrapped in StrictMode, the same operations produced the same results.
I have not tested Firefox, Safari, touch devices, or screen readers. The code in this article also does not include handling for reopening a submenu on the left side when it would run off the right edge of the screen.

- 1. Writing the menu contents as a tree with children
- 2. Holding the open submenu as an array of parent ids
- 3. Waiting briefly before switching submenus when the pointer lands on an item
- 4. With the keyboard, → opens a submenu, and ← and Esc go back up one level
- 5. Giving the button aria-haspopup and aria-expanded
Writing the menu contents as a tree with children
The menu items are passed as an array of objects in the following shape. An item with children is the parent item that opens a submenu.
export type MenuItem = {
id: string;
label: string;
children?: MenuItem[]; // If present, a submenu opens from this item
};
export const menuItems: MenuItem[] = [
{ id: 'new', label: '新規作成' },
{ id: 'open', label: '開く' },
{
id: 'export',
label: '書き出す',
children: [
{ id: 'pdf', label: 'PDF' },
{
id: 'image',
label: '画像',
children: [
{ id: 'png', label: 'PNG' },
{ id: 'jpeg', label: 'JPEG' },
{ id: 'webp', label: 'WebP' },
],
},
{ id: 'text', label: 'テキスト' },
],
},
{
id: 'share',
label: '共有',
children: [
{ id: 'copy-link', label: 'リンクをコピー' },
{ id: 'mail', label: 'メールで送る' },
],
},
{ id: 'delete', label: '削除' },
];
Items of the same shape can also appear inside children, so you can add as many levels as you need. In this example, "Image" under "Export" has a third-level menu.
Holding the open submenu as an array of parent ids
The component's state consists of two values: whether the top-level menu opened by the button is open (open), and an array of the ids of the parent items of the open submenus (openPath).
const [open, setOpen] = useState(false);
// Holds the ids of the parent items of open submenus, from the top level down. [] means no submenu is open
const [openPath, setOpenPath] = useState<string[]>([]);
When "Image" under "Export" is also open, openPath becomes ['export', 'image']. renderMenu renders the items at level level. Only the item whose id matches openPath[level] is set to expanded, and below it, renderMenu calls itself to render the submenu.
const renderMenu = (list: MenuItem[], level: number, parents: MenuItem[]) => {
const parent = parents.at(-1) ?? null;
return (
<ul
role="menu"
id={menuId(parent ? parent.id : 'root')}
aria-labelledby={parent ? itemId(parent.id) : `${baseId}-button`}
className={level === 0 ? 'menu' : 'menu submenu'}
>
{list.map((item) => {
const expanded = openPath[level] === item.id;
return (
<li role="none" key={item.id}>
<div
role="menuitem"
id={itemId(item.id)}
tabIndex={-1}
aria-haspopup={item.children ? 'menu' : undefined}
aria-expanded={item.children ? expanded : undefined}
aria-controls={item.children && expanded ? menuId(item.id) : undefined}
onPointerEnter={(e) => handlePointerEnter(level, item, e.currentTarget)}
onKeyDown={(e) => handleKeyDown(e, level, item, parents)}
onClick={() => {
if (!item.children) return select([...parents, item]);
// When a parent item is clicked, open its submenu without waiting
cancelTimer();
setOpenPath((path) => [...path.slice(0, level), item.id]);
}}
>
{item.label}
{item.children && <span aria-hidden="true">▸</span>}
</div>
{item.children && expanded && renderMenu(item.children, level + 1, [...parents, item])}
</li>
);
})}
</ul>
);
};
I structured the ul and li elements to follow the menu and menubar pattern in WAI-ARIA. In this pattern, the submenu's menu is placed inside the same menu directly after its parent menuitem. The parent menuitem gets menu as its aria-haspopup value, and whether the submenu is visible is expressed with aria-expanded set to true or false. The li elements are only there for layout, so I gave them the none role to keep them from appearing as list items in the accessibility tree.
After opening "Export", I exported the accessibility tree with Playwright and got the following. The name of the submenu comes from the text of the parent item that aria-labelledby points to.
- button "メニュー" [expanded]
- menu "メニュー":
- menuitem "新規作成"
- menuitem "開く"
- menuitem "書き出す" [expanded]
- menu "書き出す":
- menuitem "PDF"
- menuitem "画像"
- menuitem "テキスト"
- menuitem "共有"
- menuitem "削除"
CSS is responsible for placing the submenu to the right of the parent item. I set each li to position: relative, and place the submenu ul at left: 100% so that it sits at the right edge of its li.
.menu li { position: relative; }
.submenu { top: -5px; left: 100%; margin: 0 0 0 2px; }
Waiting briefly before switching submenus when the pointer lands on an item
If the submenu switches the moment the pointer lands on an item, a diagonal movement causes problems. Suppose you move diagonally from "Export" toward "Text" lower in its submenu. Partway through, the path crosses over "Share", which is the item one row below. At that moment the "Share" submenu opens and the target "Text" disappears.

To deal with this, the component waits briefly after the pointer lands on another item before switching submenus. If the pointer lands on an item inside the submenu while it is waiting, the timer is cancelled at that point, so "Share", which the pointer only passed over, does not open.
// When the pointer lands on item, an item at the level-th level
const handlePointerEnter = (level: number, item: MenuItem, el: HTMLElement) => {
el.focus();
cancelTimer();
// For a parent item, open its submenu. Otherwise, close the submenus below this level
const update = () =>
setOpenPath((path) => (item.children ? [...path.slice(0, level), item.id] : path.slice(0, level)));
if (hoverDelay === 0) update();
else timerRef.current = window.setTimeout(update, hoverDelay);
};
pointerenter is the event that fires when the pointer enters an element. The update that runs inside the timer passes a function to setOpenPath. When a function is passed, React uses it as an updater function that builds the next state from the state at that moment. Even if openPath changes while the timer is waiting, the next array is still built from the latest value.
In testing, I moved the pointer from "Export" to "Text" in 12 steps, every 16ms (about 0.2 seconds). The results with a hover delay of 0ms and of 200ms were as follows.
hoverDelay=0: 通った項目 [共有 → リンクをコピー → メールで送る] / 最後の位置にある項目: メールで送る / 0.3秒後: 開いているメニュー: [メニュー, 共有] / フォーカス: メールで送る / 選んだ項目:(まだ選んでいません)
hoverDelay=200: 通った項目 [共有 → 画像 → テキスト] / 最後の位置にある項目: テキスト / 0.3秒後: 開いているメニュー: [メニュー, 書き出す] / フォーカス: テキスト / 選んだ項目:(まだ選んでいません)
Without waiting, the menu switched to the "Share" submenu as soon as the pointer crossed over "Share", and the item where the pointer ended was "Email it". With the 200ms wait, even though the pointer passed over "Share" and "Image", the "Export" submenu stayed open, and the pointer ended on "Text".
Because of the wait, opening a submenu by simply hovering over a parent item also takes a little longer. In testing, the submenu was not yet open at 100ms after the pointer landed on the item, and it was open at 250ms.
書き出すに乗って100ms 開いているメニュー: [メニュー] / フォーカス: 書き出す / 選んだ項目:(まだ選んでいません)
書き出すに乗って250ms 開いているメニュー: [メニュー, 書き出す] / フォーカス: 書き出す / 選んだ項目:(まだ選んでいません)
For users who want a submenu to open without waiting, pressing a parent item opens it right away without using a timer (in onClick in renderMenu). I hovered over "Share" and clicked it immediately, and the submenu was open right after the click.
共有を押した直後 開いているメニュー: [メニュー, 共有] / フォーカス: 共有 / 選んだ項目:書き出す > 画像 > PNG
With the keyboard, → opens a submenu, and ← and Esc go back up one level
For keyboard operation, I followed the keyboard behavior for an open menu described in the menu pattern mentioned above.
| Key | Action |
|---|---|
| ↓ and ↑ | Move to the next and previous item in the same level (wrap around to the other end at the edges) |
| → | If it is a parent item, open its submenu and move to the first item |
| Enter, Space | If it is a parent item, open its submenu. Otherwise, select the item and close the menu |
| ← | Close the submenu and return to the parent item |
| Esc | Close the current menu and return to where it was opened from (the parent item or the button) |
| Tab | Close all menus and move to the next element |
// Called when a key is pressed on item at the level-th level. parents holds the parent items at the levels above
const handleKeyDown = (e: KeyboardEvent<HTMLElement>, level: number, item: MenuItem, parents: MenuItem[]) => {
const el = e.currentTarget;
const siblings = [...el.closest('[role="menu"]')!.querySelectorAll<HTMLElement>(':scope > li > [role="menuitem"]')];
const index = siblings.indexOf(el);
const parent = parents.at(-1);
switch (e.key) {
case 'ArrowDown':
siblings[(index + 1) % siblings.length].focus();
break;
case 'ArrowUp':
siblings[(index - 1 + siblings.length) % siblings.length].focus();
break;
case 'Enter':
case ' ':
case 'ArrowRight':
if (!item.children) {
if (e.key === 'ArrowRight') return;
select([...parents, item]);
break;
}
// Open the submenu and move focus to its first item
cancelTimer();
flushSync(() => setOpenPath([...openPath.slice(0, level), item.id]));
focusFirstIn(menuId(item.id));
break;
case 'ArrowLeft':
case 'Escape':
cancelTimer();
if (!parent) {
if (e.key === 'Escape') closeAll(true);
return;
}
// Return to the level above and move focus to the parent of the open submenu
setOpenPath(openPath.slice(0, level - 1));
document.getElementById(itemId(parent.id))?.focus();
break;
case 'Tab':
closeAll(false);
return; // Does not stop the default action (moving to the next element)
default:
return;
}
e.preventDefault();
};
When a submenu is opened with →, focus must move to its first item. However, the ul of the submenu is not in the DOM until React re-renders after the state changes. To handle this, I call setOpenPath inside flushSync so the DOM is updated synchronously, and then focusFirstIn looks for the element. The official reference recommends using flushSync only as a last resort. Here I use it only when opening a submenu with →, Enter, or Space, and when opening the top-level menu from the button.
For Tab, I return without calling preventDefault, because I want the menus to close and focus to move to the next element as the browser normally does.
Below is the result of pressing ↓ with focus on the button. The first ↑ wraps around to "Delete" at the end, then moves through "Export" and "Image" to open the third level. After that, ← and Esc are used to go back.
ArrowDown 開いているメニュー: [メニュー] / フォーカス: 新規作成 / 選んだ項目:書き出す > 画像 > PNG
ArrowUp 開いているメニュー: [メニュー] / フォーカス: 削除 / 選んだ項目:書き出す > 画像 > PNG
ArrowDown 開いているメニュー: [メニュー] / フォーカス: 新規作成 / 選んだ項目:書き出す > 画像 > PNG
ArrowDown 開いているメニュー: [メニュー] / フォーカス: 開く / 選んだ項目:書き出す > 画像 > PNG
ArrowDown 開いているメニュー: [メニュー] / フォーカス: 書き出す / 選んだ項目:書き出す > 画像 > PNG
ArrowRight 開いているメニュー: [メニュー, 書き出す] / フォーカス: PDF / 選んだ項目:書き出す > 画像 > PNG
ArrowDown 開いているメニュー: [メニュー, 書き出す] / フォーカス: 画像 / 選んだ項目:書き出す > 画像 > PNG
ArrowRight 開いているメニュー: [メニュー, 書き出す, 画像] / フォーカス: PNG / 選んだ項目:書き出す > 画像 > PNG
ArrowLeft 開いているメニュー: [メニュー, 書き出す] / フォーカス: 画像 / 選んだ項目:書き出す > 画像 > PNG
Escape 開いているメニュー: [メニュー] / フォーカス: 書き出す / 選んだ項目:書き出す > 画像 > PNG
Escape 開いているメニュー: [] / フォーカス: メニュー / 選んだ項目:書き出す > 画像 > PNG
Pressing ← and Esc closed one level at a time, and pressing Esc at the top-level menu closed everything and returned focus to the button. When Space was pressed on an end item ("Copy link"), the item was selected and the menu closed, and focus returned to the button, just as with Enter.
Space 開いているメニュー: [] / フォーカス: メニュー / 選んだ項目:共有 > リンクをコピー
When Tab was pressed, all menus closed and focus moved to the next button.
Tab 開いているメニュー: [] / フォーカス: メニューの次のボタン / 選んだ項目:共有 > リンクをコピー
Giving the button aria-haspopup and aria-expanded
The button that opens the menu follows the menu button pattern in WAI-ARIA. It has aria-haspopup="menu", and whether it is open is expressed with aria-expanded. This pattern requires that Enter and Space open the menu and move to the first item, and opening with ↓ is optional. Enter and Space reach onClick as button clicks, so onKeyDown only handles ↓.
return (
<div className="dropdown" ref={rootRef}>
<button
ref={buttonRef}
id={`${baseId}-button`}
type="button"
aria-haspopup="menu"
aria-expanded={open}
aria-controls={open ? menuId('root') : undefined}
onClick={() => (open ? closeAll(false) : openRoot())}
onKeyDown={(e) => {
if (!open && e.key === 'ArrowDown') {
e.preventDefault();
openRoot();
}
}}
>
{label}
</button>
{open && renderMenu(items, 0, [])}
</div>
);
When a click happens outside the menu, the pointerdown listener on document catches it and closes everything. To determine whether the pressed element is inside the div that wraps the button and the menu, it uses contains.
// If the user presses outside the menu, close everything
useEffect(() => {
if (!open) return;
const onPointerDown = (e: PointerEvent) => {
if (!rootRef.current?.contains(e.target as Node)) closeAll(false);
};
document.addEventListener('pointerdown', onPointerDown);
return () => document.removeEventListener('pointerdown', onPointerDown);
}, [open]);
When an item is selected or the menu is closed with Esc, focus returns to the button. When a click happens outside, the user is trying to operate something else, so focus is not returned. In testing, after pressing PNG, focus was on the button ("Menu"), and after pressing outside, focus was nowhere.
PNG を押した 開いているメニュー: [] / フォーカス: メニュー / 選んだ項目:書き出す > 画像 > PNG
外を押した 開いているメニュー: [] / フォーカス: body(どこにもない) / 選んだ項目:書き出す > 画像 > PNG
This difference is controlled by the returnFocus argument of closeAll, which handles all the closing logic. Selecting an item and pressing Esc pass true, and clicking outside and Tab pass false.
const closeAll = (returnFocus: boolean) => {
cancelTimer();
setOpen(false);
setOpenPath([]);
if (returnFocus) buttonRef.current?.focus();
};
Posted by 86
Related Posts

How to Center an Element on the Screen with CSS
To center a dialog or notice on the scre ...

Building a Looping News Ticker in React
A React component that keeps news text s ...

How to Use CSS Container Queries in React to Change Layout by Placement
How to show the same React component sid ...

How to Change Checkbox Colors with CSS accent-color
To match the blue of checkboxes and radi ...

How to Show Online or Offline Status on a React Screen
I built a React display that shows "Offl ...
