How to use arrow keys to navigate from input field to ReactJS searchable autocomplete list?

349 Views Asked by At

Using this codepen, I would like to add in the functionality of arrowing up and down through the dropdown items.

To do this, I think I need to remove the activeSuggestion className from the first item in the list (possibly by using -1 in the index or something), until the user presses the down arrow. When that happens, I would also like remove focus from the input field and bring it to the first item in the list.

Desired functionality:

  • User types in "A" to autocomplete, filtering out a few items (focus is in the input field)
  • User presses down arrow, which brings focus from input field to "Alligator". Alligator is now the "activeSuggestion" and is highlighted.
  • User arrows back up, bringing the focus back to the input field. Alligator is no longer highlighted.

enter image description here

I tried messing with the index, activesuggestion, and userinput values (+1, 0, -1). This snippet comes from my codepen

  onKeyDown = (e) => {
    const { activeSuggestion, filteredSuggestions } = this.state;

    // User pressed the enter key
    if (e.keyCode === 13) {
      this.setState({
        activeSuggestion: 0,
        userInput: filteredSuggestions[activeSuggestion]
      });
    }
    // User pressed the up arrow
    else if (e.keyCode === 38) {
      if (activeSuggestion === 0) {
        return;
      }

      this.setState({ activeSuggestion: activeSuggestion - 1 });
    }
    // User pressed the down arrow
    else if (e.keyCode === 40) {
      if (activeSuggestion - 1 === filteredSuggestions.length) {
        return;
      }

      this.setState({ activeSuggestion: activeSuggestion + 1 });
    }
  };

Thanks for your help - I really appreciate any feedback!

0

There are 0 best solutions below