I want to add the keyboard navigation with (arrow up, arrow down, tab and enter) to my select component, so the user can navigate within the items in the select box using the keyboard, how can this be done?
export function SelectComponent({
...
}: SelectProps) {
const [isOpen, setIsOpen] = useState(false);
const [search, setSearch] = useState("");
const [focusedIndex, setFocusedIndex] = useState("");
const searchResults = useMemo(() => {
if (!search) return options;
return options.filter(item =>
item.value.toString().toLowerCase().includes(search.toLowerCase())
);
}, [options, search]);
const keyboardNavigation = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowDown") {
setIsOpen(true);
}
if (event.key === "ArrowUp") {
////Here to add the code
}
if (event.key === "Escape") {
////Here to add the code
}
if (event.key === "Enter") {
////Here to add the code
}
};
return (
<div onKeyDown={event => keyboardNavigation(event)}>
<input onClick={() => setIsOpen(!isOpen)} value={search} onChange={event => setSearch(event?.target.value)}/>
<div>
{searchResults.map((option, index) => {
return (
<div tabIndex={0} key={option.label} onClick={() => { setIsOpen(false); setSearch(option.value.toString());}}>{option.value}</div>);
})}
</div></div>);}