0Pricing
React Academy · Lesson

Keyboard Navigation in Suggestion Lists

Handle ArrowUp, ArrowDown, Enter, and Escape keys to navigate and select suggestions without a mouse.

Handling onKeyDown on the Input

Attach the keyboard handler to the onKeyDown event on the input element, not onKeyPress (deprecated) or onKeyUp. keyDown fires before the character appears in the input, which allows you to intercept ArrowDown, ArrowUp, Enter, and Escape before they have any default browser effect.

ArrowDown Key Behavior

When the user presses ArrowDown, increment selectedIndex by 1, clamped to a maximum of suggestions.length - 1: setSelectedIndex(prev => Math.min(prev + 1, suggestions.length - 1)). Also call e.preventDefault() to stop the cursor from jumping to the end of the input text, which is the default browser behavior for ArrowDown in text inputs.

All lessons in this course

  1. Controlled Input with Suggestion List
  2. Keyboard Navigation in Suggestion Lists
  3. Async Suggestions with Debounce
  4. Accessibility for Autocomplete Widgets
← Back to React Academy