Detect when the Backspace key is pressed in React.js

avatar

Borislav Hadzhiev

Last updated: Apr 18, 2022

banner

Photo from Unsplash

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;

When the onKeyDown prop is added to an input field, we only listen for keys the user pressed 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.

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.