Borislav Hadzhiev
Mon Apr 18 2022·1 min read
Photo by Jordan Bauer
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 pressed 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.