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_2y ago
kB_
kB_2y ago
You could possibly put an onKeyPress event on your root component Why is using document outdated/not a good solution?
mrnicericee
mrnicericee2y 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
shinesloveOP2y ago
I saw issue with it because it goes out of the v-dom, instead of using useRef
shineslove
shinesloveOP2y 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
Leonidas2y ago
Keep it simple: <div onKeyDown={(e)=>{ if (e.key === „ArrowRight“) doThat() if (e.key === „ArrowLeft“) doThis() }}> ….. </div>
Want results from more Discord servers?
Add your server