I have the following hook:
export default function useKeyPress(targetKey: string) {
const [keyPressed, setKeyPressed] = useState(false);
const downHandler = (e) => {
if (e.repeat) {
return;
}
if (e.key === targetKey) {
console.log(targetKey);
setKeyPressed(true);
}
}
const upHandler = ({ key }) => {
if (key === targetKey) {
setKeyPressed(false);
}
}
useEffect(() => {
if (window !== undefined) {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
}
return () => {
if (window !== undefined) {
window.removeEventListener('keydown', downHandler)
window.removeEventListener('keyup', upHandler)
}
}
}, [])
return keyPressed;
}
The console.log(targetKey) always returns the result twice. I.e if I hit V, it will console log it twice.
I am trying to implement a function call in my React component that calls a function once control + v is hit. But the issue is that it calls it twice, thus not following specification.
I've tried using useState booleans to intercept a second call but it hasn't worked.
I use it in the following manner:
const pressedControl = useKeyPress('Control');
const pressedV = useKeyPress('v');
useEffect(() => {
if (pressedControl && pressedV) {
console.log("Ctrl + V");
}
}, [pressedC, pressedV]);
e.preventDefault()on the first line within yourdownHandlerfunction?keydownandkeyupwhich fires both when someone clicks a key ... also you're adding your events twice for bothcontrolandvkeys