Skip to content

Instantly share code, notes, and snippets.

@skorotkiewicz
Created April 22, 2021 13:01
Show Gist options
  • Save skorotkiewicz/e11f78e5cd22ad1a3d019053de9f61ba to your computer and use it in GitHub Desktop.
Save skorotkiewicz/e11f78e5cd22ad1a3d019053de9f61ba to your computer and use it in GitHub Desktop.
React Keypress Hook
import useKeypress from "./useKeypress";
useKeypress("Escape", () => {
console.log("<kbd>ESC</kbd> pressed")
})
import { useEffect } from "react";
/**
* useKeyPress
* @param {string} key - the name of the key to respond to, compared against event.key
* @param {function} action - the action to perform on key press
*/
export default function useKeypress(key, action) {
useEffect(() => {
function onKeyup(e) {
if (e.key === key) action();
}
window.addEventListener("keyup", onKeyup);
return () => window.removeEventListener("keyup", onKeyup);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment