1

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.

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? Commented Dec 23, 2020 at 11:09

3 Answers 3

5

keep 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 />;
};

Sign up to request clarification or add additional context in comments.

1 Comment

keyCode is deprecated. We can use e.key === "Escape"
0

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.org/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.com/a/55566585/6845743

6 Comments

Mhh, same thing unfortunately. Listener isn't getting removed.
@Eight edited the answer, please take another look.
Why does useCallback help here?
because you want to trigger an action whenever a key has pressed
Using a callback doesn't seem to change anything, the behavior is exactly he same as before.
|
0

I think I figured out the issue, it was entirely my fault and the way I wrote my component.

Minimal example https://codesandbox.io/s/strange-nobel-l6eqe?file=/src/App.js

It's a lot more obvious here, but essentially the component 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:

  1. Don't write your component like this
  2. Move the listener inside a child component

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.