How to handle key press events in React?
Anyone have good resources for how to handle a key left or right event in React? I see a lot of outdated or not optimal solutions that use document.
6 Replies
SyntheticEvent – React
A JavaScript library for building user interfaces
You could possibly put an
onKeyPress
event on your root component
Why is using document
outdated/not a good solution?i also recommend doing the onKeyPress.
document can work too, but if it's in the
useEffect
, make sure you do a return
clean up on the listenerI saw issue with it because it goes out of the v-dom, instead of using useRef
A really good library I found: https://github.com/JohannesKlauss/react-hotkeys-hook
GitHub
GitHub - JohannesKlauss/react-hotkeys-hook: React hook for using ke...
React hook for using keyboard shortcuts in components. - GitHub - JohannesKlauss/react-hotkeys-hook: React hook for using keyboard shortcuts in components.
Keep it simple:
<div onKeyDown={(e)=>{
if (e.key === „ArrowRight“) doThat()
if (e.key === „ArrowLeft“) doThis()
}}>
…..
</div>