Autocomplete a Country

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Build a country picker with the WAI-ARIA combobox pattern (list autocomplete). A text input labelled "Country" has role="combobox", aria-autocomplete="list", aria-expanded "true" while the list shows and "false" otherwise, and aria-controls holding the list's id. The countries come from a countries prop (the starter has a default list). Typing shows the ones whose names start with the text, ignoring case, in their given order, as role="option" elements inside a role="listbox". Show the list only while the text isn't empty and something matches; otherwise leave it out or hide it with the hidden attribute. Keep DOM focus in the input throughout and use aria-activedescendant: the input's aria-activedescendant holds the active option's id, and that option has aria-selected="true". No option is active until an arrow key is pressed, and typing makes none active again; remove aria-activedescendant whenever none is. The Down arrow makes the next option active (the first if none is), and Up the previous one (the last if none is), wrapping round at both ends. Enter picks the active option: the input then holds its name and the list closes. Clicking an option picks it too. Escape closes the list and keeps the text.

Your code must pass

  • The input is a combobox labelled "Country", closed at first
  • Typing shows the matching countries in a listbox
  • Arrow keys move the active option while focus stays in the input
  • Enter picks the active option and closes the list
  • Clicking an option picks it
  • Escape closes the list and keeps the text