-
Notifications
You must be signed in to change notification settings - Fork 0
/
useOnKeyPress.js
34 lines (27 loc) · 1 KB
/
useOnKeyPress.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* Credits: https://wattenberger.com/blog/react-hooks */
const useOnKeyPress = (targetKey, onKeyDown, onKeyUp, isDebugging=false) => {
const [isKeyDown, setIsKeyDown] = useState(false)
const onKeyDownLocal = useCallback(e => {
if (isDebugging) console.log("key down", e.key, e.key != targetKey ? "- isn't triggered" : "- is triggered")
if (e.key != targetKey) return
setIsKeyDown(true)
if (typeof onKeyDown != "function") return
onKeyDown(e)
})
const onKeyUpLocal = useCallback(e => {
if (isDebugging) console.log("key up", e.key, e.key != targetKey ? "- isn't triggered" : "- is triggered")
if (e.key != targetKey) return
setIsKeyDown(false)
if (typeof onKeyUp != "function") return
onKeyUp(e)
})
useEffect(() => {
addEventListener('keydown', onKeyDownLocal)
addEventListener('keyup', onKeyUpLocal)
return () => {
removeEventListener('keydown', onKeyDownLocal)
removeEventListener('keyup', onKeyUpLocal)
}
}, [])
return isKeyDown
}