Created
June 25, 2019 18:26
-
-
Save jmegs/547776c61a1440323c591160d6291f1f to your computer and use it in GitHub Desktop.
This file contains 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
export function useKeyEvent(code, keyFunction, deps) { | |
keyFunction = React.useCallback(keyFunction, deps) | |
React.useEffect(() => { | |
function pressKey(event) { | |
if (event.code === code) { | |
keyFunction(event) | |
} | |
} | |
document.addEventListener('keydown', pressKey) | |
return function removeListener() { | |
document.removeEventListener('keydown', pressKey) | |
} | |
}, [code, keyFunction]) | |
} | |
/* | |
How to use: | |
useKeyEvent("Escape", () => console.log("You pressed the escape key")) | |
find key events at https://keycode.info | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment