Get Input value when Enter key is pressed in React

avatar

Borislav Hadzhiev

Sat Apr 23 20222 min read

banner

Photo by John Salvino

Get Input value when Enter key is pressed in React #

To get an input's value when the Enter key is pressed in React:

  1. Set the onKeyDown prop on the input field.
  2. When a user presses a key, check if the key is Enter.
  3. Access the input field's value from the state variable.
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log(event.key); if (event.key === 'Enter') { event.preventDefault(); // 👇️ access input value from state console.log(message); // 👇️ access input value from event object // console.log(event.target.value) console.log('User pressed Enter ✅'); } }; return ( <div> <input type="text" id="message" name="message" value={message} onChange={event => setMessage(event.target.value)} onKeyDown={handleKeyDown} /> </div> ); }; export default App;

get input value on enter

We used the useState hook to store the value of the input field.

When the onKeyDown prop is added to an input field, we only listen for keys the user pressed when the input field is focused.

Every time the user presses a key, the handleKeyDown function runs. We use the key property on the event object to 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 handleKeyDown = event => { if (event.key === 'Enter') { event.preventDefault(); console.log('User pressed Enter ✅'); // 👇️ access input value console.log(event.target.value); } }; return ( <div> <input type="text" id="message" name="message" onKeyDown={handleKeyDown} /> </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.

This approach is useful when we need to run some logic when the user has finished typing and don't want to use a form with an onSubmit event handler.

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