Created
July 19, 2021 18:05
-
-
Save danielgary/955b6f8b3cfe67a6356dc8f31df0a11f to your computer and use it in GitHub Desktop.
React Hook for Control + Key
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 { useCallback, useEffect, useState } from 'react' | |
export const useKeyboardShortcut = (key: string, callback: (keyEvent: KeyboardEvent) => void) => { | |
const [pressed, setPressed] = useState(false) | |
const keyPressHandler = useCallback( | |
(ev: KeyboardEvent) => { | |
if (ev.ctrlKey || ev.metaKey) { | |
if (ev.key.toLowerCase() === key.toLowerCase()) { | |
ev.preventDefault() | |
ev.stopPropagation() | |
ev.stopImmediatePropagation() | |
if (ev.type === 'keydown' && !pressed) { | |
callback(ev) | |
} | |
setPressed(ev.type === 'keydown') | |
} | |
} | |
}, | |
[key, callback, pressed, setPressed] | |
) | |
useEffect(() => { | |
if (keyPressHandler) { | |
window.addEventListener('keydown', keyPressHandler) | |
window.addEventListener('keyup', keyPressHandler) | |
return () => { | |
window.removeEventListener('keydown', keyPressHandler) | |
window.removeEventListener('keyup', keyPressHandler) | |
} | |
} | |
}, [keyPressHandler]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment