I'm currently having trouble creating a keypress listener (or any listener) on a component.
Essentially I would like to have my listener triggered whenever I press "ESC", but I'm finding myself blocked.
My function component 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 component is mounted, the window
listener is correctly added. Unfortunately after the component 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.