'How can I get onKeyDown event to work in Next.js/React

I'm building a website using Next.js, and currently I'm trying to get a simple function to run when pressing a key. The problem I'm having is that the onKeyDown event isn't being triggered like I expected. My code is as follows: <main onKeyDown={e => console.log("Key pressed")}>

Currently it's placed in the "main" element, which is the top root element of this component. I've tried placing the onKeyDown event in many of the other elements as well, without luck. I'm not sure if it's the placement which causes issues or my lack of understanding of how to use this event. Any help would be appreciated.

As for now I simply want it to write something in the console so that I can see that it triggers. I've tried using onKeyPress instead, as well as assigning a function to the event instead of a lambda expression, which shouldn't make a difference.



Solution 1:[1]

In your component, use useEffect to add(and remove) the event listener to the document.

const Component = () => {

  useEffect(() => {
    const keyDownHandler = (e) => console.log(`You pressed ${e.code}.`);
    document.addEventListener("keydown", keyDownHandler);

    // clean up
    return () => {
      document.removeEventListener("keydown", keyDownHandler);
    };
  }, []);

  return <main>Press a key</main>;
};

You may even make a custom hook (beware of the dependency list):

const useKeyDown = (handler, deps = []) => {
  useEffect(() => {
    document.addEventListener("keydown", handler);
    // clean up
    return () => {
      document.removeEventListener("keydown", handler);
    };
  }, deps);
};

const Component = () => {
  useKeyDown((e) => console.log(`You pressed ${e.code}.`), []);
  return <main>Press a key</main>;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1