I'm currently having trouble creating a keypress listener (or any listener) on a ponent.
Essentially I would like to have my listener triggered whenever I press "ESC", but I'm finding myself blocked.
My function ponent is pretty simple, it looks like this:
const Component = () => {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.isComposing || e.keyCode === 27) {
console.log('do something');
}
};
window.addEventListener('keydown', handler, false);
return () => window.removeEventListener('keydown', handler, false);
}, []);
return <div />;
};
When my ponent is mounted, the window
listener is correctly added. Unfortunately after the ponent unmounts, the event listener is not removed.
So I tried adding the event listener specifically to the div I'm mounting:
const Component = () => {
const ref = useRef(null);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.isComposing || e.keyCode === 27) {
console.log('do something');
}
};
const divRef = ref.current as any;
divRef.addEventListener('keydown', handler, false);
return () => divRef.removeEventListener('keydown', handler, false);
}, []);
return <div ref={ref} />;
};
But this just doesn't work at all and the handler is never called.
I'm currently having trouble creating a keypress listener (or any listener) on a ponent.
Essentially I would like to have my listener triggered whenever I press "ESC", but I'm finding myself blocked.
My function ponent is pretty simple, it looks like this:
const Component = () => {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.isComposing || e.keyCode === 27) {
console.log('do something');
}
};
window.addEventListener('keydown', handler, false);
return () => window.removeEventListener('keydown', handler, false);
}, []);
return <div />;
};
When my ponent is mounted, the window
listener is correctly added. Unfortunately after the ponent unmounts, the event listener is not removed.
So I tried adding the event listener specifically to the div I'm mounting:
const Component = () => {
const ref = useRef(null);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.isComposing || e.keyCode === 27) {
console.log('do something');
}
};
const divRef = ref.current as any;
divRef.addEventListener('keydown', handler, false);
return () => divRef.removeEventListener('keydown', handler, false);
}, []);
return <div ref={ref} />;
};
But this just doesn't work at all and the handler is never called.
Share Improve this question asked Dec 23, 2020 at 10:58 lpetruccilpetrucci 1,7396 gold badges30 silver badges53 bronze badges 1-
I can't replicate the issue. The keyboard events don't even seem to fire on a
div
. May you make sure the example is a minimal reproducible example? – evolutionxbox Commented Dec 23, 2020 at 11:09
3 Answers
Reset to default 5keep the handler outside useEffect, that should work. we would just be attaching that function on mount and removing on unmount.
const Component = () => {
const handler = (e: KeyboardEvent) => {
if (e.isComposing || e.keyCode === 27) {
console.log('do something');
}
};
useEffect(() => {
window.addEventListener('keydown', handler, false);
return () => window.removeEventListener('keydown', handler, false);
}, []);
return <div />;
};
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply setting a state using the previous state, it's best to use the callback pattern and register the event listeners only on the initial mount. If you do not use the callback pattern (https://reactjs/docs/hooks-reference.html#usecallback) the listeners reference along with its lexical scope is being used by the event listener but a new function is created with updated closure on new render and hence in the handler you will not be able to the updated state
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(prevUserText => `${prevUserText}${key}`);
}
}, []);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
according to this answer : https://stackoverflow./a/55566585/6845743
I think I figured out the issue, it was entirely my fault and the way I wrote my ponent.
Minimal example https://codesandbox.io/s/strange-nobel-l6eqe?file=/src/App.js
It's a lot more obvious here, but essentially the ponent where the listener was created wasn't actually being unmounted, I was just unmounting its contents which obviously meant the listener wasn't getting removed.
Solutions are:
- Don't write your ponent like this
- Move the listener inside a child ponent