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
kB_
kB_15mo ago
kB_
kB_15mo ago
You could possibly put an onKeyPress event on your root component Why is using document outdated/not a good solution?
mrnicericee
mrnicericee15mo ago
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 listener
shineslove
shineslove15mo ago
I saw issue with it because it goes out of the v-dom, instead of using useRef
shineslove
shineslove13mo ago
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.
Leonidas
Leonidas13mo ago
Keep it simple: <div onKeyDown={(e)=>{ if (e.key === „ArrowRight“) doThat() if (e.key === „ArrowLeft“) doThis() }}> ….. </div>