How to listen to keypress for document in React?

Sometimes, we want to listen to keypress for document in React.

In this article, we’ll look at how to listen to keypress for document in React.

How to listen to keypress for document in React?

To listen to keypress for document in React, we can call document.addEventListener in the useEffect hook callback.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  const handleKeyDown = (e) => {
    console.log(e.key);
  };

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);

    return () => document.removeEventListener("keydown", handleKeyDown);
  }, []);

  return <div></div>;
}

In the useEffect callback, we call document.addEventListener with 'keydown' and the handleKeyDown function.

Next, we return a function that calls document.removeEventListener with the same arguments to remove the event listener when App is unmounted.

In handleKeyDown, we get the key that’s pressed with the e.key property.

Now when we’re focused on the window and the press keys on the keyboard, we should see the key value logged.

Conclusion

To listen to keypress for document in React, we can call document.addEventListener in the useEffect hook callback.