Created
November 9, 2021 09:31
-
-
Save eriksachse/1acf2e6c8ec4c399a536dcb3af39e23c to your computer and use it in GitHub Desktop.
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
| function useKeyPress(targetKey) { | |
| // State for keeping track of whether key is pressed | |
| const [keyPressed, setKeyPressed] = useState<boolean>(false); | |
| // If pressed key is our target key then set to true | |
| function downHandler({ key }) { | |
| if (key === targetKey) { | |
| setKeyPressed(true); | |
| } | |
| } | |
| // If released key is our target key then set to false | |
| const upHandler = ({ key }) => { | |
| if (key === targetKey) { | |
| setKeyPressed(false); | |
| } | |
| }; | |
| // Add event listeners | |
| useEffect(() => { | |
| window.addEventListener("keydown", downHandler); | |
| window.addEventListener("keyup", upHandler); | |
| // Remove event listeners on cleanup | |
| return () => { | |
| window.removeEventListener("keydown", downHandler); | |
| window.removeEventListener("keyup", upHandler); | |
| }; | |
| }, []); // Empty array ensures that effect is only run on mount and unmount | |
| return keyPressed; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: