Skip to content

A Combobox

The Course
•
20 min study

A combobox is a text box with a list of suggestions: search boxes, address pickers, tag inputs. It's one of the hardest widgets to make accessible, because two things need the keyboard at once: typing in the box, and moving through the list.

Pick a topic React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Combobox from "./Combobox.jsx"; import { topics } from "./topics.js"; export default function App() { const [chosen, setChosen] = useState(null); return ( <main> <h1>Pick a topic</h1> <Combobox label="Topic" options={topics} onSelect={setChosen} /> <p className="muted">Chosen: {chosen ?? "nothing yet"}</p> </main> ); } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } export const topics = [ "Compound components", "Controlled props", "Render props", "Imperative handles", "External stores", "Selectors", "State machines", "Suspense", "Request cache", "Lazy loading", "Profiling", "Windowing", "Activity", "Dialogs", "Comboboxes", ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Type st, use the Down and Up arrows, press Enter. Type again and press Escape.

Focus stays in the input

The solution is that focus never leaves the text box. The arrow keys change which option is active, and the input tells assistive technology which one that is:

JavaScript
aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined}

aria-activedescendant holds the id of the active option. A screen reader announces that option as if it were focused, while the user can still type.

The roles and states

ElementAttributes
The inputrole="combobox", aria-expanded (is the list showing?), aria-controls (the list's id), aria-autocomplete="list"
The listrole="listbox"
Each suggestionrole="option", a unique id, aria-selected on the active one

Each id is built from useId, so two comboboxes on a page never collide.

The keys

KeyDoes
Down / UpOpen the list, and move the active option
EnterChoose the active option
EscapeClose the list, keeping the text
TypingFilter the list, and clear the active option

A mouse detail

Each option has onMouseDown={(e) => e.preventDefault()}. Without it, pressing the mouse on an option would take focus from the input first. Keeping focus in the input is the whole design.

Predict

Type zz, so nothing matches. What does the input's aria-expanded say, and is a list on screen?

Check your prediction

aria-expanded is still true, because typing opened it, but no list is rendered, because there are no matches. A screen reader would announce an expanded list that isn't there. The exercise fixes it.

Exercise

An honest, closing popup

Two fixes, both about the popup's real state.

  1. Make aria-expanded true only when the list is actually on screen, and show No topics match under the input when it isn't.
  2. Close the list when focus leaves the input, for example when the user presses Tab. Clicking an option with the mouse must still choose it.

When both work, delete the options' onMouseDown line, and click an option. Write down what happens and why, then put the line back.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Combobox from "./Combobox.jsx"; import { topics } from "./topics.js"; export default function App() { const [chosen, setChosen] = useState(null); return ( <main> <h1>Pick a topic</h1> <Combobox label="Topic" options={topics} onSelect={setChosen} /> <p className="muted">Chosen: {chosen ?? "nothing yet"}</p> </main> ); } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } export const topics = [ "Compound components", "Controlled props", "Render props", "Imperative handles", "External stores", "Selectors", "State machines", "Suspense", "Request cache", "Lazy loading", "Profiling", "Windowing", "Activity", "Dialogs", "Comboboxes", ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The accessibility state must describe the popup actually rendered, so aria-expanded and the list should come from one true/false value, which covers the no-matches case too. For closing, the input has an event for losing focus. Think about the order of events when the mouse presses an option: what happens to the input's focus before the click arrives?

Hint 2: a first step

Type zz and inspect the input: aria-expanded="true" with no list. Work out the value that says whether the list is shown, use it in both places, and check zz again. Then add an onBlur handler to the input that closes the list, and press Tab after typing st: the list should disappear. Click an option to check that choosing still works.

Show one solution
JavaScript
const showList = open && matches.length > 0;
JSX
<input
  ...
  aria-expanded={showList}
  onBlur={() => {
    setOpen(false);
    setActiveIndex(-1);
  }}
/>
{showList && (
  <ul role="listbox" ...>...</ul>
)}
{open && matches.length === 0 && <p className="muted">No topics match</p>}

Without the onMouseDown line, clicking an option does nothing. Pressing the mouse on the option moves focus away from the input, which fires onBlur, which closes the list. By the time the mouse button comes up, the option has gone, so no click happens on it. preventDefault() on mousedown stops the focus move, so the input never blurs during a click. Closing on blur and keeping focus in the input are two halves of the same design.

Was this article helpful?

Your response is saved on this device.