I have a React component which displays a list of "autocomplete" recommendations as the user is typing into the search bar. I am trying to allow for the user to also navigate the list by using the arrow keys and enter key.
When the user presses the down key for the first time, the focus variable increases by one and the HTML focus goes to the first recommendation. If they press it again, it goes to the focus variable increases by one again, and the HTML focus moves to the second recommendation, and so on. Similarly, when the user presses the up key it decreases the focus by one and moves the HTML focus to the previous recommendation. In addition, there are measures to ensure the focus index does not go outside of the possible range as well as resetting the focus index to zero when the value of the search bar changes.
I am encountering this strange error that when overriding the focus index value, it will function properly only when using the down key, and then when I press the up key it will change to the previous value form before the override. In some case this can cause the focus index to go outside of the range and then crash, since when you type longer searches it narrows down the list of recommendations.
Here are some screen shots of the console output for the focus index when searching only one letter:
Now I'll show what happens when I narrow the search and then navigate the recommendations:
Here is a working codesandbox link:
https://codesandbox.io/s/jolly-tu-7itsm?fontsize=14&hidenavigation=1&theme=dark




