Navigating dropdown results using arrow keys, while keeping focus on textbox

Viewed 3070

I am trying to implement a type-able dropdown component in React. I have managed to implement a trivial dropdown list, where results are shown to a user based on what they type in the dropdown's textbox, and results keep updating as they type.

Now I want users to be able to navigate through the dropdown results using up and down arrow keys. But for that I guess I will need to have focus on 2 elements at the same time? One for the type-able textbox, so users can keep typing, and the other for the search results, so users can navigate between them using keys? I know that focus can only be on one element at a time, so how do I achieve this?

As an example of what I am asking for, see this snapshot of a type-able dropdown:

enter image description here

As you can see, the focus is on the textbox here, but it also seems to be on the highlighted element, so the up-down keys work on it. I took this image from the react-select project. How would you guess they achieved it?

My trivial dropdown list code currently looks as follows:

let dropdownOptions = [];
for (let i = 0; i < searchResults.length; i++) {
    dropdownOptions.push(
        <div key={i} tabIndex={"0"}
             onMouseDown={() => {
                    // code to set the dropdown's selected value when
                    // a dropdown option is clicked, then hide the dropdown
                }}
             onKeyPress={(e) => {
                    // this is where the code to navigate between 
                    // results using arrow keys will go.
                }}
        >
             {searchResults[i].value}
        </div>);
}

This is the array of <div>s which contains the search results of the dropdown. These divs form the options that are shown to the user when they type something in the textbox.

So, is trying to focus on multiple elements the right way to go? If not, what else can I do to implement this?

0 Answers
Related