Created
December 8, 2022 17:13
-
-
Save dmdez/5c31d71998988c0b1425596e56cc0987 to your computer and use it in GitHub Desktop.
React Hook Keypress Callback
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, useRef } from 'react'; | |
type KeyboardRef = (event: KeyboardEvent) => void; | |
const useKeypress = (keys: string[], handler?: (e: KeyboardEvent) => void) => { | |
const eventListenerRef = useRef<KeyboardRef | null>(null); | |
useEffect(() => { | |
eventListenerRef.current = (event: KeyboardEvent) => { | |
if (Array.isArray(keys) ? keys.includes(event.key) : keys === event.key) { | |
handler?.(event); | |
} | |
}; | |
}, [keys, handler]); | |
useEffect(() => { | |
const eventListener = (event: KeyboardEvent) => { | |
if ( eventListenerRef ) { | |
eventListenerRef.current?.(event); | |
} | |
}; | |
window.addEventListener('keydown', eventListener); | |
return () => { | |
window.removeEventListener('keydown', eventListener); | |
}; | |
}, []); | |
}; | |
export default useKeypress; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment