Detect when the Backspace key is pressed in React.js

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

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

To detect when the user pressed the Backspace key in React.js:

  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 Backspace.
  3. Invoke a function or run some logic if it is.
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log('User pressed: ', event.key); // console.log(message); if (event.key === 'Backspace') { // 👇️ your logic here console.log('Backspace key pressed ✅'); } }; return ( <div> <input value={message} onChange={event => setMessage(event.target.value)} onKeyDown={handleKeyDown} id="message" name="message" autoComplete="off" /> </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 presses when the input field is focused.

detect backspace press

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

The keydown event is triggered anytime the user presses a key on their keyboard.

Every time the event is triggered, we check if the pressed key is the Backspace key and run some logic if it is.

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

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

The code for this article is available on GitHub

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

I've also written an article on how to detect when the user presses the Enter key.

If you need to turn off autocomplete on an input field, check out the following article.

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.