Last updated: Apr 6, 2024
Reading time·2 min
To detect when the user pressed the Backspace key in React.js:
onKeyDown
prop to the input
element.Backspace
.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 presses when
the input field is focused.
The key
property on the KeyboardEvent
object returns the value of the key that was
pressed by the user.
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.
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.