'Scroll on list with arrow keys
so I have a searcher I'm building, and I struggling with the arrow keys navigation. I can't workaround to scroll through the navigation, I don't know if I'm explaining myself.enter image description here
for example, if I have all the results (or more than 7 in this case), and I want to navigate to the last one, the state changes ok (the highlighted bg moves through the focused option good), but the list doesn't scroll, so when one that is not in view is focused, I can't see it and I have to scroll with the trackpad.
My code:
const [search, setSearch] = useState('')
const [filteredPosts, setFilteredPosts] = useState<ContentfulPost[]>(posts)
const [focusedPost, setFocusedPost] = useState(0)
useEffect(() => {
const filter = search
? posts?.filter(
(p) =>
p.title.toLocaleLowerCase().includes(search.toLocaleLowerCase()) ||
p.author[0].name
.toLocaleLowerCase()
.includes(search.toLocaleLowerCase()) ||
p.tag.toLocaleLowerCase().includes(search.toLocaleLowerCase())
)
: posts
setFilteredPosts(filter)
}, [search, posts])
const keyPress = useCallback((event) => {
if (event.key === 'Escape') {
setIsOpen(false)
} else if (event.keyCode === 38) {
setFocusedPost((prev) => (prev <= 0 ? 0 : prev - 1))
} else if (event.keyCode === 40) {
setFocusedPost((prev) =>
prev >= filteredPosts?.length - 1 ? filteredPosts?.length - 1 : prev + 1
)
}
}, [])
useEffect(() => {
document.addEventListener('keydown', keyPress, false)
return () => {
document.removeEventListener('keydown', keyPress, false)
}
}, [keyPress])
<div
className={clsx('rounded-xl overflow-auto flex flex-col', s.modal)}
>
<div className="sticky top-0 pb-2 bg-white">
<input
ref={searcherInputRef}
onChange={(e) => {
const value = e.target.value
setSearch(value)
}}
type="text"
className="text-gray-800 border-b border-gray-300 border-solid px-6 flex min-w-full pt-5 pb-4 placeholder-gray-500 focus:outline-none"
placeholder="Buscar..."
/>
</div>
<div className="px-3 flex flex-col pb-2">
{filteredPosts?.map((post, idx) => (
<Link
key={idx}
href={`/${getSectionSlug(post.category)}/${post.slug}`}
>
<a
onMouseEnter={() => setFocusedPost(idx)}
className={clsx(
'px-6 py-4 rounded-lg text-gray-800 noDecoration',
{
'bg-gray-100': focusedPost == idx
}
)}
>
{post.title}{' '}
<span className="ml-1 text-14 text-gray-600">
en {post.category}
</span>
</a>
</Link>
))}
</div>
</div>
Does anybody knows how to fix this? thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
