Created
February 2, 2023 19:57
-
-
Save thr0wn/649c7288e14324cf4a2dcce72e4fa73d to your computer and use it in GitHub Desktop.
Keydown handler in typescript
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 React, { useEffect, useRef, useState } from 'react'; | |
export const KEYCODE_ENTER = 'Enter'; | |
export const KEYCODE_ESC = 'Escape'; | |
export const KEYCODE_SPACEBAR = 'Space'; | |
export const useKeyDown = (key: string) => { | |
const [pressed, setPressed] = useState(false); | |
const match = (event: KeyboardEvent) => key === event.code; | |
const onDown = (event: KeyboardEvent) => { | |
if (match(event)) setPressed(true); | |
}; | |
const onUp = (event: KeyboardEvent) => { | |
if (match(event)) setPressed(false); | |
}; | |
useEffect(() => { | |
window.addEventListener('keydown', onDown); | |
window.addEventListener('keyup', onUp); | |
return () => { | |
window.removeEventListener('keydown', onDown); | |
window.removeEventListener('keyup', onUp); | |
}; | |
}, [key]); | |
return pressed; | |
}; | |
export const useKeyDownCallback = (key: string, callback: () => void) => { | |
const pressed = useKeyDown(key); | |
const ref = useRef(pressed); | |
useEffect(() => { | |
if (!pressed === ref.current) { | |
callback(); | |
} | |
ref.current = pressed; | |
}, [pressed]); | |
}; | |
export const onKeyBoardEvent = (key: string, callback: () => void) => (event: React.KeyboardEvent) => { | |
if (key === event.code) { | |
callback(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment