Handle the onKeyPress event in React

avatar

Borislav Hadzhiev

Sun May 01 20222 min read

banner

Photo by Scott Jackson

Handle the onKeyPress event in React #

To handle the onKeyPress event in React:

  1. Set the onKeyPress prop on the element.
  2. Use the key property on the event object to get the key the user pressed.
  3. For example, if (event.key === 'Enter') {}.
App.js
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;

react handle onkeypress event

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.

App.js
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.

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