Building an Accessible Dropdown Menu in React
Build a keyboard friendly menu button in React with ARIA roles.
Dropdown menus are everywhere: account menus, "more actions" buttons, settings toggles. They're also easy to get wrong. A div that shows a list on click works with a mouse, but keyboard and screen reader users can't tell it's a menu, can't open it reliably and can't move through the options.
The good news is the WAI-ARIA Authoring Practices describe exactly how a menu button should behave. Let's build one in React with hooks.
How a menu button should behave
- The button opens the menu with a click, Enter, Space or ArrowDown, and focus moves to the first item. ArrowUp opens it and focuses the last item.
- ArrowDown and ArrowUp move between items and wrap around at the ends.
- Home and End jump to the first and last item.
- Enter or Space selects the focused item and closes the menu.
- Escape closes the menu and moves focus back to the button.
- Tab closes the menu and moves on to the next element on the page.
- Clicking outside the menu closes it.
Unlike a modal, a menu doesn't trap focus. If you're building a modal instead, see Focus Trapping for Better Web Accessibility.
The markup
<buttonid="account-button"aria-haspopup="true"aria-expanded="false"aria-controls="account-menu">Account</button><ul id="account-menu" role="menu" aria-labelledby="account-button" hidden><li role="menuitem" tabindex="-1">Profile</li><li role="menuitem" tabindex="-1">Settings</li><li role="menuitem" tabindex="-1">Sign out</li></ul>
aria-haspopup="true"tells screen readers the button opens a menu.aria-expandedsays whether the menu is open, andaria-controlspoints to it.role="menu"androle="menuitem"give the list menu semantics, so screen readers announce "Profile, menu item, 1 of 3".
Roving tabIndex
Only one item in the menu should be focusable at a time. The active item gets
tabIndex={0} and every other item gets tabIndex={-1}. This is called a
roving tabindex. The arrow keys move the active index, and we call .focus() on
the new item. Items with -1 can still be focused with JavaScript, they're
just skipped when tabbing.
The DropdownMenu component
Putting this all together:
import { useEffect, useRef, useState } from "react"const DropdownMenu = ({ id, label, items }) => {const [isOpen, setIsOpen] = useState(false)const [activeIndex, setActiveIndex] = useState(0)const buttonRef = useRef(null)const menuRef = useRef(null)const itemRefs = useRef([])const buttonId = `${id}-button`const menuId = `${id}-menu`const lastIndex = items.length - 1// Focus the active item whenever the menu opens or the index changesuseEffect(() => {if (isOpen) {itemRefs.current[activeIndex].focus()}}, [isOpen, activeIndex])// Close the menu when clicking outside of ituseEffect(() => {if (!isOpen) returnconst handleMouseDown = (event) => {if (!menuRef.current.contains(event.target) &&!buttonRef.current.contains(event.target)) {setIsOpen(false)}}document.addEventListener("mousedown", handleMouseDown)return () => document.removeEventListener("mousedown", handleMouseDown)}, [isOpen])const openMenu = (index) => {setActiveIndex(index)setIsOpen(true)}const closeMenu = () => {setIsOpen(false)buttonRef.current.focus()}const selectItem = (item) => {item.onSelect()closeMenu()}const handleButtonKeyDown = (event) => {if (event.key === "ArrowDown") {event.preventDefault()openMenu(0)} else if (event.key === "ArrowUp") {event.preventDefault()openMenu(lastIndex)}}const handleMenuKeyDown = (event) => {switch (event.key) {case "ArrowDown":event.preventDefault()setActiveIndex((index) => (index === lastIndex ? 0 : index + 1))breakcase "ArrowUp":event.preventDefault()setActiveIndex((index) => (index === 0 ? lastIndex : index - 1))breakcase "Home":event.preventDefault()setActiveIndex(0)breakcase "End":event.preventDefault()setActiveIndex(lastIndex)breakcase "Enter":case " ":event.preventDefault()selectItem(items[activeIndex])breakcase "Escape":event.preventDefault()closeMenu()breakcase "Tab":setIsOpen(false)breakdefault:break}}return (<div className="dropdown"><buttonref={buttonRef}id={buttonId}aria-haspopup="true"aria-expanded={isOpen}aria-controls={menuId}onClick={() => (isOpen ? setIsOpen(false) : openMenu(0))}onKeyDown={handleButtonKeyDown}>{label}</button><ulref={menuRef}id={menuId}role="menu"aria-labelledby={buttonId}hidden={!isOpen}onKeyDown={handleMenuKeyDown}>{items.map((item, index) => (<likey={item.label}ref={(el) => (itemRefs.current[index] = el)}role="menuitem"tabIndex={index === activeIndex ? 0 : -1}onClick={() => selectItem(item)}>{item.label}</li>))}</ul></div>)}export default DropdownMenu
There's a lot here, so let's walk through it:
- The first
useEffectmoves focus. Opening the menu or changingactiveIndexfocuses the matching item throughitemRefs. The menu is already visible by the time the effect runs, so focus works. - The second
useEffectadds a mousedown listener only while the menu is open, and closes it when the click lands outside both the button and the menu. - A button already fires
onClickfor Enter and Space, sohandleButtonKeyDownonly needs to handle the arrow keys. handleMenuKeyDownis a single listener on the ul. Key events from the focused li bubble up to it, so we don't need a handler on every item.closeMenusends focus back to the button. Tab doesn't use it because the user is moving on to the next element and we don't want to pull focus back.aria-expanded={isOpen}renders "true" or "false", so screen readers always know the state.
The id prop is used to build unique ids for aria-controls and
aria-labelledby, so you can have more than one menu on a page.
Using the component
const Header = () => (<header><DropdownMenuid="account"label="Account"items={[{ label: "Profile", onSelect: () => console.log("Profile") },{ label: "Settings", onSelect: () => console.log("Settings") },{ label: "Sign out", onSelect: () => console.log("Sign out") },]}/></header>)
Try it with only your keyboard: Tab to the button, press ArrowDown, move around with the arrows, Home and End, then press Escape. Focus should end up back on the button every time. Then try it with VoiceOver or NVDA to hear how each item is announced.
Nothing selected yet
Note: A menu is for actions. If the options navigate to other pages, a list of
regular links inside a disclosure (a button with aria-expanded) is often a
better fit.
If you'd rather use a tested component, Reach UI and Headless UI both ship a menu button that follows this pattern.
Have some feedback on this post? .