Detect when the Backspace key is pressed in React.js

avatar

Borislav Hadzhiev

Mon Apr 18 20221 min read

banner

Photo by Jordan Bauer

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.