I implemented a function to navigate through a list and scroll when I hit the last item visible in the list, this is my code so far:
const arrowNavigation = (
e: React.KeyboardEvent<HTMLInputElement>
) => {
if (selectedCountry.current) console.log(selectedCountry.current.last());
if (e.key === 'ArrowDown') {
if (selectedCountryIndex < autoCompleteSuggestions.length - 1)
setSelectedCountryIndex(selectedCountryIndex + 1);
if (selectedCountryIndex > 3)
if (selectedCountry.current && dataList.current) {
console.log(selectedCountry.current.offsetHeight);
dataList.current.scrollTop +=
selectedCountry.current.offsetHeight;
}
} else if (e.key === 'ArrowUp') {
if (selectedCountryIndex - 1 >= 0)
setSelectedCountryIndex(selectedCountryIndex - 1);
if (selectedCountryIndex > 3)
if (selectedCountry.current && dataList.current) {
dataList.current.scrollTop -=
selectedCountry.current.offsetHeight;
}
} else if (e.key === 'Enter') {
if (textInput.current)
textInput.current.value =
autoCompleteSuggestions[selectedCountryIndex];
setInputValue(autoCompleteSuggestions[selectedCountryIndex]);
}
};
To explain the code:
dataList is the ul.
selectedCountry is the li element that I am currently on.
selectedCountryIndex is the index of element that I am currently on.
autoCompleteSuggestions is a list of country suggestions based on the input I've given.
So my approach was to wait till selectedCountryIndex is at a certain point to start scrolling but this is really just a hardcoded solution if my list view has more visible items it wouldn't really work, is there a way to know how many visible items the ul has? or maybe know the position of the visible items in the ul (like first last and so on..).
Also, as you can see in the gif when I scroll down it works perfectly, but when I scroll up, I start seeing the next element little by little, I am not sure why that's happening, so if you have any idea about that as well let me know.

