Created
December 30, 2018 22:09
-
-
Save mmazzarolo/d157c83e697fd46510bec4c3a5003f2c to your computer and use it in GitHub Desktop.
A React hook for handling keypresses
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
import { useState, useEffect, useRef } from "react"; | |
interface Parameters { | |
key: string; | |
ctrlKey?: boolean; | |
shiftKey?: boolean; | |
metaKey?: boolean; | |
onKeyDown?: (e: KeyboardEvent) => void; | |
onKeyUp?: (e: KeyboardEvent) => void; | |
} | |
const checkKeyValidity = (e: KeyboardEvent, params: Parameters) => { | |
return ( | |
e.key === params.key && | |
e.ctrlKey === !!params.ctrlKey && | |
e.metaKey === !!params.metaKey && | |
e.shiftKey === !!params.shiftKey | |
); | |
}; | |
export function useKeyboardPress(params: Parameters) { | |
const [isKeyDown, setIsKeyDown] = useState(false); | |
const shouldDisableKeyDownUpdate = useRef(false); | |
const handleKeyDown = (e: KeyboardEvent) => { | |
const isKeyValid = checkKeyValidity(e, params); | |
if (isKeyValid) { | |
if (params.onKeyDown) { | |
params.onKeyDown(e); | |
} | |
if (!shouldDisableKeyDownUpdate.current) { | |
shouldDisableKeyDownUpdate.current = true; | |
setIsKeyDown(true); | |
} | |
} | |
}; | |
const handleKeyUp = (e: KeyboardEvent) => { | |
shouldDisableKeyDownUpdate.current = false; | |
if (params.onKeyUp) { | |
params.onKeyUp(e); | |
} | |
setIsKeyDown(false); | |
}; | |
useEffect(() => { | |
window.document.addEventListener("keydown", handleKeyDown); | |
window.document.addEventListener("keyup", handleKeyUp); | |
return () => { | |
window.document.removeEventListener("keydown", handleKeyDown); | |
window.document.removeEventListener("keyup", handleKeyUp); | |
}; | |
}, []); | |
return isKeyDown; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage examples
Check if the tab key is down
Invoke a callback when the A key is pressed
Combination of the two examples above
Override CTRL + F search (on Windows)