Created
April 22, 2021 13:01
-
-
Save skorotkiewicz/e11f78e5cd22ad1a3d019053de9f61ba to your computer and use it in GitHub Desktop.
React Keypress Hook
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 useKeypress from "./useKeypress"; | |
useKeypress("Escape", () => { | |
console.log("<kbd>ESC</kbd> pressed") | |
}) |
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 { 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