I've seen similar posts on this issue, but when I try to implement what they suggested, it never works. I have the active state and my search results that are return on dispatch. When I type into the input search or click on it the menu opens below it and shows the results, yet when I hit the arrow keys it stays within the input bar and does not iterate/focus through each list item. I would like to make it so that when I hit either the down or up arrow key it would iterate through the search results and I can hit enter on any of them to trigger the search.
const [active, setActive] = useState(0)
const searchResults = useSelector((state) => Object.values(state.searchReducer.Search))
const keyDown = (e) => {
if(e.key === 38 && searchResults.length > 0){
setActive(active - 1)
}else if(e.key === 40 && active < searchResults.length - 1){
setActive(active + 1)
}
}
<BsSearch className="search-icon" />
<form onSubmit={handleSubmit}>
<input
onClick={() => setMenu(true)}
className="search-input"
autoFocus
onKeyDown={keyDown}
type="search"
placeholder="Search"
onChange={(e) => setSearchVal(e.target.value)}
value={searchVal}
/>
</form>
{menu && (
<div className="search-cont">
{searchResults.length > 0 ? (
searchResults?.map((ele, i) => {
return (
<NavLink onClick={(() => {setSearchVal('')})} key={i} className="spot-
links" to={`/users/${ele.id}`}>
<div
className="search-results-list"
id={active === i ? 'active' : null}
>
{ele.username}
</div>
</NavLink>
);
})
```