Get Input value when Enter key is pressed in React


Borislav Hadzhiev

Last updated: Apr 23, 2022


Photo from Unsplash

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.
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( console.log('User pressed Enter ✅'); } }; return ( <div> <input type="text" id="message" name="message" value={message} onChange={event => setMessage(} 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.

const App = () => { const handleKeyDown = event => { if (event.key === 'Enter') { event.preventDefault(); console.log('User pressed Enter ✅'); // 👇️ access input value console.log(; } }; 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.