Created
December 30, 2020 02:29
-
-
Save jeremytenjo/60dfb1ae98668861b08dce621ca1cff4 to your computer and use it in GitHub Desktop.
useKeyPress React hook with multiple key support
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
export default function useKeyPress(keys, onPress) { | |
keys = keys.split(' ').map((key) => key.toLowerCase()) | |
const isSingleKey = keys.length === 1 | |
const pressedKeys = useRef([]) | |
const keyIsRequested = (key) => { | |
key = key.toLowerCase() | |
return keys.includes(key) | |
} | |
const addPressedKey = (key) => { | |
key = key.toLowerCase() | |
const update = pressedKeys.current.slice() | |
update.push(key) | |
pressedKeys.current = update | |
} | |
const removePressedKey = (key) => { | |
key = key.toLowerCase() | |
let update = pressedKeys.current.slice() | |
const index = update.findIndex((sKey) => sKey === key) | |
update = update.slice(0, index) | |
pressedKeys.current = update | |
} | |
const downHandler = ({ key }) => { | |
const isKeyRequested = keyIsRequested(key) | |
if (isKeyRequested) { | |
addPressedKey(key) | |
} | |
} | |
const upHandler = ({ key }) => { | |
const isKeyRequested = keyIsRequested(key) | |
if (isKeyRequested) { | |
if (isSingleKey) { | |
pressedKeys.current = [] | |
onPress() | |
} else { | |
const containsAll = keys.every((i) => pressedKeys.current.includes(i)) | |
removePressedKey(key) | |
if (containsAll) { | |
onPress() | |
} | |
} | |
} | |
} | |
useEffect(() => { | |
window.addEventListener('keydown', downHandler) | |
window.addEventListener('keyup', upHandler) | |
return () => { | |
window.removeEventListener('keydown', downHandler) | |
window.removeEventListener('keyup', upHandler) | |
} | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage (Codesandbox):