Last active
October 24, 2024 18:24
-
-
Save paulohfev/874e47aee64715ee556fe00187f5c65e to your computer and use it in GitHub Desktop.
useKeyDown hook w/ TypeScript
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 { useEffect } from 'react'; | |
| import { KeyboardKey } from 'enums/keyboardKey'; | |
| export const useKeyPress = (callback: (T?: any) => void, keys: KeyboardKey[]) => { | |
| const onKeyDown = (event: KeyboardEvent) => { | |
| const wasAnyKeyPressed = keys.some((key) => event.key === key); | |
| if (wasAnyKeyPressed) { | |
| event.preventDefault(); | |
| callback(); | |
| } | |
| }; | |
| useEffect(() => { | |
| document.addEventListener('keydown', onKeyDown); | |
| return () => { | |
| document.removeEventListener('keydown', onKeyDown); | |
| }; | |
| }, [onKeyDown]); | |
| }; | |
| // enums/KeyboardKey.ts | |
| export enum KeyboardKey { | |
| escape = 'Escape', | |
| enter = 'Enter', | |
| } | |
| // Example usage: | |
| useKeyPress(() => { | |
| someCallback(); | |
| }, [KeyboardKey.escape]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment