In this section, we will look at how to get input field values in React. There are two different ways of getting the input values in react, one is controlled and the other is through uncontrolled components. We will look at both techniques with examples.

Controlled Components

In the controlled components, the user input is controlled by the react component that creates the form. We always keep track of the user input and store it in a state. The state value is used as the input value which is used for displaying the content in the input field.

import { useState } from 'react';
function App() {

  const handleForm = (e) => {
    e.preventDefault();
    console.log(value);
  };

  const [value, setValue] = useState('');
  return(
    <>
      <form onSubmit={handleForm}>
        <input type='text' value={value} onChange={(e) => setValue(e.target.value)} />
        <button>Submit</button>
      </form>
    </>
  );
};

export default App;

In this example, we have declared a value state using the useState. As you can see, we are calling a function on every keystroke, passing the event - e. The value of the input field is retrieved through the event target value e.target.value and is set to value using the setValue function.

On submitting the form, we are logging the stored value. Note, the preventDefault() is used to prevent the default behaviour of the browser from loading the page.

Uncontrolled components

In uncontrolled components, the form is handled by the DOM instead of the react component. In this case, we make use of the ref to get the input text value.

import { useRef } from 'react';

function App() {
  const inputEl = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(inputEl.current.value);
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input type="text" ref={inputEl} />
        <button>Submit</button>
      </form>
    </>
  );
}

export default App;

In the above example, we initialize the inputEl variable to useRef(). In the input field, we assign the ref property to inputEl. To get the value of the input, we need to access the current property of the ref object (inputEl.current.value).