Next.js Discord

Discord Forum

What’s the best way to implement keyboard navigation?

Answered
Atlantic herring posted this in #help-forum
Open in Discord
Atlantic herringOP
Like, what do most people use (packages, best practices, etc.) to build that kind of keyboard navigation you see on sites like Vercel?
Answered by American black bear
you can use plain old useEffect and the built in keyboard event listener
View full answer

4 Replies

American black bear
you can use plain old useEffect and the built in keyboard event listener
Answer
American black bear
useEffect(() => {
  function handlePressShortcut(e) {
    // handle when user presses 
  }
  
  // create event listener
  document.addEventListener("keydown", e => handlePressShortcut(e))
  
  // don't forget to remove the event listener to prevent memory leaks
  return () => 
}, [])
if you want a package approach this looks great, though I've never used it myself