How to Get an Input Field's Value in React

Last updated on November 19, 2022
How to Get an Input Field's Value in React

To get the value of an input field in React:

  1. Create a state variable to store the input field's value.
  2. Set an onChange event handler on the input field.
  3. In the event handler, assign event.target.value to the state variable.
  4. The state variable will contains the input field's value at any given time.

For example:

App.js

import { useState } from 'react';

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

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

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

  const handleClick = () => {
    //  "message" stores input field value
    setUpdated(message);
  };

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

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

      <h2>Updated: {updated}</h2>

      <button onClick={handleClick}>Update</button>
    </div>
  );
}

With the useState hook, we create a state variable (message) to store the input field's current value. We also create another state variable (updated) that will be updated with the input field value when the button is clicked.

We set an onChange event handler on the input field to execute an action. In the handler, we use the Event object's target property to access the object representing 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 get the current value of the input field.

So in the onClick event handler we set on the button, we use setUpdated(message) to update the updated variable with the input field's current value.

Get input value with ref

Alternatively, we can use a ref to get the value of an input field in React. After setting the ref on the input, we'll be able to use the ref object to access the input field's current value in the event handler.

App.js

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>
  );
}

We set an onKeyDown event listener on the input to perform an action when a key is pressed. In this listener, we use the KeyboardEvent object's key property to check if the key pressed is Enter, and if so, we use the ref object to get the input's value and update the updated variable with it.

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 simple and doesn’t need instant validation, and values only need to be accessed on submission.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also