Created
January 7, 2024 18:36
-
-
Save GalindoSVQ/fe98e7e91259c2c0d8221270ddd0adb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from 'react'; | |
| React.useEffectEvent = React.experimental_useEffectEvent; | |
| export default function useKeyPress(key, cb, options = {}) { | |
| const { event = 'keydown', target = window ?? null, eventOptions } = options; | |
| const onListen = React.useEffectEvent(cb); | |
| React.useEffect(() => { | |
| const handler = (event) => { | |
| if (event.key === key) { | |
| onListen(event); | |
| } | |
| }; | |
| target.addEventListener(event, handler, eventOptions); | |
| return () => { | |
| target.removeEventListener(event, handler, eventOptions); | |
| }; | |
| }, [key, target, event, eventOptions]); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-gkugso