Detect when the Enter or Escape key is pressed in React.js

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
4 min

banner

# Table of Contents

  1. Detect when the Enter key is pressed in React.js
  2. Detect when the Esc key is pressed in React.js

If you need to detect when the Esc key is pressed, click on the second subheading.

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

To detect when the Enter 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 Enter.
  3. Invoke a function or run some logic if the pressed key is Enter.
App.js
import {useEffect} from 'react'; const App = () => { const myFunction = () => { // Your logic here console.log('pressed Enter โœ…'); }; useEffect(() => { const keyDownHandler = event => { console.log('User pressed: ', event.key); if (event.key === 'Enter') { event.preventDefault(); // ๐Ÿ‘‡๏ธ Your logic here myFunction(); } }; document.addEventListener('keydown', keyDownHandler); return () => { document.removeEventListener('keydown', keyDownHandler); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }; export default App;

detect when enter key is pressed in react

The code for this article is available on GitHub
If you need to detect when the Enter key is pressed while the user types in an input field, scroll down to the next code snippet.

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 enter press

In the function, we simply check if the user pressed the Enter 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.

I've also written an article on how to submit a form using the Enter key.

# Detect when user pressed Enter key when typing

To detect when the user pressed the Enter key when typing in an input field:

  1. Add the onKeyDown prop to the input element.
  2. Every time the user presses a key in the input field, check if the pressed key is Enter.
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log('User pressed: ', event.key); if (event.key === 'Enter') { // ๐Ÿ‘‡๏ธ Your logic here console.log('Enter key pressed โœ…'); } }; return ( <div> <input onChange={event => setMessage(event.target.value)} onKeyDown={handleKeyDown} id="message" name="message" /> </div> ); }; export default App;
The code for this article is available on GitHub

When the onKeyDown prop is added to an input field, we only listen for keys the user pressed when the input field is focused.

This is different from the previous code snippet, in which we added the keydown event listener on the document element.

detect enter press input field

This approach is useful when we need to run some logic when the user has finished typing and don't want to use a form with an onSubmit event handler.

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

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

If you need to detect when the user presses the Backspace key, click on the following article.

# 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.
App.js
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;
The code for this article is available on GitHub

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 and 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.

If you need to handle the onKeyDown event on a Div element, click on the link and follow the instructions.

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.

Copyright ยฉ 2024 Borislav Hadzhiev