Skip to content

Instantly share code, notes, and snippets.

@ChaseH88
Created January 10, 2021 22:50
Show Gist options
  • Select an option

  • Save ChaseH88/3d15fa3c81342841e876aa172ff0e809 to your computer and use it in GitHub Desktop.

Select an option

Save ChaseH88/3d15fa3c81342841e876aa172ff0e809 to your computer and use it in GitHub Desktop.
This is a React hook that attaches keyup and keydown handlers to the window to detect whether or not a particular key code has been pressed.
import { useState, useEffect } from "react";
type KeyCode = { keyCode: number };
/**
* Attaches keyup and keydown handlers to the window to detect
* whether or not a particular key code has been pressed.
* @param targetKey The key code
* @returns {boolean}
* @example const isPressed = useKeyPress(13);
*/
const useKeyPress = (targetKey: number): boolean => {
const { addEventListener, removeEventListener } = window;
const [keyPressed, setKeyPressed] = useState(false);
const handler = ({ keyCode }: KeyCode, h: boolean) => (
keyCode === targetKey && setKeyPressed(h)
);
useEffect(() => {
addEventListener('keydown', (e: KeyboardEvent) => handler(e, true));
addEventListener('keyup', (e: KeyboardEvent) => handler(e, false));
return () => {
removeEventListener('keydown', (e: KeyboardEvent) => handler(e, true));
removeEventListener('keyup', (e: KeyboardEvent) => handler(e, false));
};
}, []);
return keyPressed;
}
export { useKeyPress };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment