Created
July 11, 2024 13:26
-
-
Save ali-master/ccd0a3925dde038280958e75891d4f64 to your computer and use it in GitHub Desktop.
React Keyboard hot keys Hooks
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 { useEffect } from "react"; | |
import hotkeys from "hotkeys-js"; | |
// Types | |
import type { KeyHandler } from "hotkeys-js"; | |
/** | |
* Filter function to ignore hotkeys when typing in an input, textarea or select | |
* @param {KeyboardEvent} event | |
* @returns {boolean} | |
*/ | |
hotkeys.filter = (event: KeyboardEvent) => { | |
const target = (event.target || event.srcElement) as HTMLElement; | |
const { tagName } = target; | |
let flag = true; | |
// ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select> | |
if ( | |
target.isContentEditable || | |
target.getAttribute("role") === "option" || | |
((tagName === "INPUT" || tagName === "TEXTAREA" || tagName === "SELECT") && | |
"readOnly" in target && | |
!target.readOnly) | |
) { | |
flag = false; | |
} | |
return flag; | |
}; | |
/** | |
* Hook to bind hotkeys | |
* @description This hook binds a hotkey to a handler function and unbinds it when the component is unmounted or the hotkey changes | |
* @param {string} key | |
* @param {KeyHandler} handler | |
* @example | |
* useHotkeys('ctrl+shift+s', () => console.log('You pressed ctrl+shift+s')); | |
* useHotkeys("b", () => { | |
* doWhatever(); | |
* }); | |
* useHotkeys("command+ctrl+shift+a", () => { | |
* doSomethingElse(); | |
* }) | |
*/ | |
const useHotkeys = (key: string, handler: KeyHandler) => { | |
useEffect(() => { | |
hotkeys(key, handler); | |
return () => { | |
hotkeys.unbind(key, handler); | |
}; | |
}, [key, handler]); | |
}; | |
export default useHotkeys; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment