Last active
December 20, 2019 15:27
-
-
Save madflanderz/de3c0bde62a9aa2662ffe1588b448a09 to your computer and use it in GitHub Desktop.
Hook for responding to keyboard events.
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 { useState, useEffect } from "react" | |
type HookProps = { | |
key?: string | |
keyCode: number | |
onKeyPress?: () => void | |
enabled?: boolean | |
} | |
/** | |
Hook for responding to keyboard events. | |
Usage: | |
// enter for open/close | |
useKeyPress({ | |
keyCode: 13, | |
onKeyPress: onKeyPress: () => console.log("Enter pressed")), | |
enabled: true, | |
}) | |
// respond the "space" key only when isOpen = true | |
useKeyPress({ | |
keyCode: 32, | |
onKeyPress: onKeyPress: () => console.log("Space pressed")), | |
enabled: isOpen, | |
}) | |
*/ | |
export function useKeyPress({ | |
key: targetKey, | |
keyCode: targetKeyCode, | |
onKeyPress, | |
enabled, | |
}: HookProps) { | |
// State for keeping track of whether key is pressed | |
const [keyPressed, setKeyPressed] = useState(false) | |
// Add event listeners | |
useEffect(() => { | |
if (!enabled) { | |
return | |
} | |
// If pressed key is our target key then set to true | |
function downHandler({ key, keyCode }: KeyboardEvent) { | |
if ( | |
(targetKey && key === targetKey) || | |
(targetKeyCode && keyCode === targetKeyCode) | |
) { | |
onKeyPress && onKeyPress() | |
setKeyPressed(true) | |
} | |
} | |
// If released key is our target key then set to false | |
const upHandler = ({ key, keyCode }: KeyboardEvent) => { | |
if ( | |
(targetKey && key === targetKey) || | |
(targetKeyCode && keyCode === targetKeyCode) | |
) { | |
setKeyPressed(false) | |
} | |
} | |
window.addEventListener("keydown", downHandler) | |
window.addEventListener("keyup", upHandler) | |
// Remove event listeners on cleanup | |
return () => { | |
window.removeEventListener("keydown", downHandler) | |
window.removeEventListener("keyup", upHandler) | |
} | |
}, [enabled, onKeyPress, targetKey, targetKeyCode]) | |
return keyPressed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment