How to Get the Value of an Input When the Enter Key is Pressed in React

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

  1. Create a state variable to store the value of the input.
  2. Set an onChange event handler on the input to update the state variable when the input field value changes.
  3. Set an onKeyDown event handler on the input.
  4. Use the state variable to access the input value in the event handler, after checking that the key pressed is Enter.

For example:

App.js

import { useState } from 'react';

export default function App() {
  const [message, setMessage] = useState('');

  const [updated, setUpdated] = useState('');

  const handleChange = (event) => {
    setMessage(event.target.value);
  };

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      // 👇 Get input value
      setUpdated(message);
    }
  };

  return (
    <div>
      <input
        type="text"
        id="message"
        name="message"
        value={message}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />

      <h2>Message: {message}</h2>

      <h2>Updated: {updated}</h2>
    </div>
  );
}
Getting an input value when the Enter key is pressed.

With the useState() hook we create a state variable (message) to store the current value of the input field. We also create another state variable (updated) that will be updated with the input field value when the Enter key is pressed.

We set an onChange event handler on the input field to make this handler get called whenever the input value changes. In the handler we use the target property of the event object to access the object that represents the input element. The value property of this object contains the input value, so we pass it to setMessage() to update message, and this reflects on the page.

After setting up the controlled input, we can now use message outside the handleChange handler to access the current value of the input field.

We use the event.key property to get the key pressed in the onKeyDown event handler. After ensuring that this key is Enter, we use setUpdated(message) to update the updated variable with the current input field value.

Get input value on Enter with event.target

We can also get the value of the input when the Enter key is pressed using the target.value property of the Event object. This is useful in cases where we are not tracking the input value with a state variable, i.e., an uncontrolled input.

import { useState } from 'react';

export default function App() {
  const [updated, setUpdated] = useState('');

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      setUpdated(event.target.value);
    }
  };

  return (
    <div>
      <input
        type="text"
        id="message"
        name="message"
        onKeyDown={handleKeyDown}
      />

      <h2>Updated: {updated}</h2>
    </div>
  );
}
Getting an input value when the Enter key is pressed.

Get input value on Enter with ref

We can also use a ref to get the value of an uncontrolled input when the Enter key is pressed.

import { useRef, useState } from 'react';

export default function App() {
  const inputRef = useRef(null);

  const [updated, setUpdated] = useState('');

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      setUpdated(inputRef.current.value);
    }
  };

  return (
    <div>
      <input
        ref={inputRef}
        type="text"
        id="message"
        name="message"
        onKeyDown={handleKeyDown}
      />

      <h2>Updated: {updated}</h2>
    </div>
  );
}

While the data in a controlled input is handled by React state, the data in an uncontrolled input is handled by the DOM itself. This is why the input in the example above doesn’t have a value prop or onChange event handler set. Instead, we access the input field value with a React ref. The DOM updates this value when the text in the input is changed.

We create a ref object with the useRef() hook and set it to the ref prop of the input. Doing this sets the current property of the ref object to the DOM object that represents the input element.

useRef() returns a mutable ref object that does not change value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState().

Although the React documentation recommends using controlled components, uncontrolled components offer some advantages. You might prefer them if the form is very simple and doesn’t need instant validation, and values only need to be accessed when the form is submitted.



Leave a Comment

Your email address will not be published. Required fields are marked *