Last active
July 15, 2021 08:16
-
-
Save luiznasciment0/9d272d8a7ed559f5345bef97eda09339 to your computer and use it in GitHub Desktop.
hook to detect keyboard key pressed and execute an action when this key is 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 { useEffect } from 'react' | |
type KeyPress = { | |
key: string | |
action: () => void | |
} | |
const useKeyPress = ({ key, action }: KeyPress) => { | |
const onKeyDown = (e: KeyboardEvent) => { | |
if (e.key === key) action() | |
document.removeEventListener('keydown', onKeyDown) | |
} | |
const onKeyUp = () => { | |
document.addEventListener('keydown', onKeyDown, { once: true }) | |
} | |
useEffect(() => { | |
document.addEventListener('keydown', onKeyDown) | |
document.addEventListener('keyup', onKeyUp) | |
return () => { | |
document.removeEventListener('keydown', onKeyDown) | |
document.removeEventListener('keyup', onKeyUp) | |
} | |
}) | |
} | |
export default useKeyPress | |
/* | |
Usage: | |
useKeyPress({ | |
key: 'ArrowDown', | |
action: () => { | |
setState(x) | |
} | |
}) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment