Borislav Hadzhiev
Sun May 01 2022·2 min read
Photo by Scott Jackson
To handle the onKeyPress
event in React:
onKeyPress
prop on the element.key
property on the event
object to get the key the user pressed.if (event.key === 'Enter') {}
.import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyPress = event => { console.log(event.key); if (event.key === 'Enter') { console.log('✅ Enter key pressed'); } // 👇️ access input value from state console.log(message); // 👇️ access input value from event object // console.log(event.target.value) }; return ( <div> <input type="text" id="message" name="message" value={message} onKeyPress={handleKeyPress} onChange={event => setMessage(event.target.value)} /> </div> ); }; export default App;
We set the onKeyPress
prop on the input
element, so every time the user
presses a button when the input
has focus, the handleKeyPress
function is
invoked.
The key
property on the event
object returns the value of the key pressed by the user.
Every time the user presses a key, the handleKeyPress
function runs and we
check if the user pressed Enter
.
The condition if (event.key === 'Enter') {}
covers all operating systems -
Windows, Mac, Linux, Android, etc.
If you don't want to track the state of the input field, you can get its value
on the target
property of the event
object.
const App = () => { const handleKeyPress = event => { console.log(event.key); if (event.key === 'Enter') { console.log('✅ Enter key pressed'); } // 👇️ access input value from event object console.log(event.target.value); }; return ( <div> <input type="text" id="message" name="message" onKeyPress={handleKeyPress} /> </div> ); }; export default App;
Instead of storing the value of the input field, we get it using the event
object.
The target
property on the event
refers to the input element.
You can view the possible keys the user might press by visiting this MDN page.