Created
September 12, 2022 12:54
-
-
Save TiagoFuelber/244fe685e179194c1b866f8c6c0d09ec to your computer and use it in GitHub Desktop.
React hook to listen to a key pressed
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
const useKeyPress = (targetKey) => { | |
const [keyPressed, setKeyPressed] = React.useState(false); | |
const downHandler = ({ key }) => { | |
if (key === targetKey) setKeyPressed(true); | |
}; | |
const upHandler = ({ key }) => { | |
if (key === targetKey) setKeyPressed(false); | |
}; | |
React.useEffect(() => { | |
window.addEventListener("keydown", downHandler); | |
window.addEventListener("keyup", upHandler); | |
return () => { | |
window.removeEventListener("keydown", downHandler); | |
window.removeEventListener("keyup", upHandler); | |
}; | |
}, []); | |
return keyPressed; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment