Detect when the Esc key is pressed in React.js


Borislav Hadzhiev

Last updated: Apr 18, 2022


Check out my new book

Detect when the Esc key is pressed in React.js #

To detect when the Esc key is pressed in React.js:

  1. Add a keydown event listener to the document element.
  2. When the user presses a key, check if the key is Esc.
  3. Invoke a function or run some logic if the pressed key is Escape.
import {useEffect} from 'react'; const App = () => { const myFunction = () => { // your logic here console.log('pressed Esc ✅'); }; useEffect(() => { const keyDownHandler = event => { console.log('User pressed: ', event.key); if (event.key === 'Escape') { event.preventDefault(); // 👇️ your logic here myFunction(); } }; document.addEventListener('keydown', keyDownHandler); // 👇️ clean up event listener return () => { document.removeEventListener('keydown', keyDownHandler); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }; export default App;

We used the useEffect hook to add a keydown event listener to the document element.

Now every time the user presses a key, the keyDownHandler function is invoked.

detect escape press

The key property on the KeyboardEvent object returns the value of the key that was pressed by the user.

In the function, we simply check if the user pressed the Esc key and if they did, we call a function.

The function we returned from the useEffect hook is used to clean up the event listener when the component unmounts.

You should always clean up any event listeners you set up to avoid memory leaks in your application.

We added the keydown event to the document element, so the event will get triggered as long as the document has focus.

This approach can be used to close pop-up menus, modals, or run any other custom logic.

You can view the possible keys the user might press by visiting this MDN page.

The condition if (event.key === 'Escape') {} covers all operating systems - Windows, Mac, Linux, Android, etc.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.