Accessible Dropdown

MediumAccessibilityKeyboardComponentsReact35 mins

by Pratik Rai

Read the full write-up

Build a dropdown from scratch — no <select>, no library.

This was asked as a machine-coding round followed by a long discussion of edge cases, keyboard support and accessibility, so the interesting half is everything past "it opens and closes".

Requirements

  1. Clicking the trigger opens the list; clicking it again, or clicking outside, closes it.

  2. Arrow Up and Arrow Down move a highlight through the options without selecting anything.

  3. Enter or Space selects the highlighted option and closes the list. Escape closes without selecting.

  4. Closing returns focus to the trigger.

  5. Opening puts the highlight on the currently selected option, not always the first.

  6. The trigger carries aria-haspopup, aria-expanded and aria-activedescendant; the list is a role="listbox" of role="option" items with aria-selected.

Notes

  • The highlight and the selection are two different things — .option-active and .option-selected style them separately.

  • Home and End jumping to the first and last option is a nice extra, and is what the ARIA listbox pattern specifies.

Hints

Loading editor…