React Forms

In HTML, form elements like <input>, <textarea>, and <select> typically maintain their own state. In React, mutable state is kept in the state property of components. We can combine the two by making the React state the "single source of truth".

Controlled Components

An input form element whose value is controlled by React in this way is called a controlled component.

JavaScript

import React, { useState } from 'react';

function NameForm() {
  const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  const handleSubmit = (e) => {
    alert('A name was submitted: ' + value);
    e.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

Handling Multiple Inputs

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

JavaScript

const handleInputChange = (e) => {
  const { name, value } = e.target;
  setInputs(values => ({...values, [name]: value}));
};

Note: With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input.