Created
January 10, 2021 22:50
-
-
Save ChaseH88/3d15fa3c81342841e876aa172ff0e809 to your computer and use it in GitHub Desktop.
This is a React hook that attaches keyup and keydown handlers to the window to detect whether or not a particular key code has been pressed.
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 { useState, useEffect } from "react"; | |
| type KeyCode = { keyCode: number }; | |
| /** | |
| * Attaches keyup and keydown handlers to the window to detect | |
| * whether or not a particular key code has been pressed. | |
| * @param targetKey The key code | |
| * @returns {boolean} | |
| * @example const isPressed = useKeyPress(13); | |
| */ | |
| const useKeyPress = (targetKey: number): boolean => { | |
| const { addEventListener, removeEventListener } = window; | |
| const [keyPressed, setKeyPressed] = useState(false); | |
| const handler = ({ keyCode }: KeyCode, h: boolean) => ( | |
| keyCode === targetKey && setKeyPressed(h) | |
| ); | |
| useEffect(() => { | |
| addEventListener('keydown', (e: KeyboardEvent) => handler(e, true)); | |
| addEventListener('keyup', (e: KeyboardEvent) => handler(e, false)); | |
| return () => { | |
| removeEventListener('keydown', (e: KeyboardEvent) => handler(e, true)); | |
| removeEventListener('keyup', (e: KeyboardEvent) => handler(e, false)); | |
| }; | |
| }, []); | |
| return keyPressed; | |
| } | |
| export { useKeyPress }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment