Categories
React Answers

How to Detect Esc Key Press in React?

Spread the love

Sometimes, we want to detect Esc Key Press in React.

In this article, we’ll look at how to detect Esc Key Press in React.

Detect Esc Key Press in React

To detect Esc Key Press in React, we can add an event listener for the keydown event.

For instance, we write:

import React, { useCallback, useEffect } from "react";

export default function App() {
  const escFunction = useCallback((event) => {
    if (event.keyCode === 27) {
      console.log("esc pressed");
    }
  }, []);

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

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

  return <div>hello</div>;
}

to define the escFunction function.

We check if event.keyCode is 27.

If it is, then the Esc key is pressed.

Then in the useEffect callback, we call document.addEventListener with 'keydown' and escFunction to use escFunction as the keydown event handler.

This will add the listener for the whole page.

And we return the function that calls document.removeEventListener with the same arguments to remove the event listener when the component is unmounted.

Therefore, when we press the Esc key, we see 'esc pressed' in the console log.

Conclusion

To detect Esc Key Press in React, we can add an event listener for the keydown event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *