Lesson 9 / 1182%

Lesson 9

Forms

22 min

Controlled inputs, submitting with onSubmit and handling several fields with a single state.

Definition

A controlled component is a form field (input,textarea,select...) whose displayed value is entirely controlled by a React component'sstate. The field does not have its own memory: it displays what the state contains, and every change made by the user triggers an update to that state. The state is therefore the form's single source of truth.

Lesson Objectives

  • Connect a field to state using value and onChange.
  • Control different field types: text, dropdown lists, checkboxes, and radio buttons.
  • Handle form submission, validation, and resetting.
  • Group multiple fields into a single state object.

Forms in React: Controlled Components

In a traditional HTML form, the browser remembers what the user types. With React, we generally prefer the component's stateto hold that value. The field is then called controlled: its value comes from state, and every keystroke updates that state.

This may seem more complicated at first, but the benefits are significant. Since the value is stored in state, you can read it at any time, validate it while the user types, transform it (for example, convert everything to uppercase), display it elsewhere on the page, or clear the field after submission. The form becomes a simple function of your state, just like the rest of your interface.

Why Control a Field?

Without a controlled field, the browser and React do not share the same information: the field contains text that your component does not know about. To retrieve that value, you would need to read it from the DOM at the last moment. With a controlled field, there is only one version of the data, stored in state, and the field always reflects it accurately.

  • Live validation: you can check the input after every keystroke.
  • Easy resetting: simply restore the state to its initial value.
  • Shared data: the value can be used by other parts of the component.

A Controlled Field

Here is the simplest possible example. The component stores the entered text in a state variable namedname. The field displays this state usingvalueand updates it usingonChange.

controlled text field
import { useState } from "react";

function NameField() {
  const [name, setName] = useState("");

  return (
    <div>
      <label htmlFor="name">Your name</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <p>Hello {name || "stranger"}!</p>
    </div>
  );
}

export default NameField;
  • value: connects the field to state.
  • onChange: updates state after every keystroke.
GIF of the name field: as you type, the Hello message updates live below the field.

How It Works, Step by Step

When the user presses a key, here is what happens:

  • The onChangeevent is triggered by the field.
  • Your function reads the new value usinge.target.value.
  • It calls setNamewith that value.
  • React renders the component again with the new state.
  • The field displays the new value, along with the "Hello ...!" message.

This entire cycle happens almost instantly. That is why the field appears to behave normally, even though React is actually deciding what is displayed.

Warning: value Without onChange

If you write valuewithout onChange, the field becomes read-only: the state never changes, so the field always displays the same value and the user can no longer type. React also displays a warning in the console.

Transforming User Input

Since the value passes through state, you can modify it before storing it. For example, here is a field that automatically converts input to uppercase and counts the characters:

uppercase and character counter
import { useState } from "react";

function CodeField() {
  const [code, setCode] = useState("");

  function handleChange(e) {
    setCode(e.target.value.toUpperCase());
  }

  return (
    <div>
      <label htmlFor="code">Promo code</label>
      <input id="code" value={code} onChange={handleChange} maxLength={10} />
      <p>{code.length} / 10 characters</p>
    </div>
  );
}

Controlled or Uncontrolled?

There is an alternative to controlled fields: let the browser manage the value and read it only when the form is submitted. This is called an uncontrolled field. You can provide an initial value using defaultValue, but React does not track what the user types.

uncontrolled field with defaultValue
function FreeField() {
  function handleSubmit(e) {
    e.preventDefault();
    const data = new FormData(e.target);
    console.log("First name:", data.get("firstName"));
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="firstName" defaultValue="Aina" />
      <button type="submit">Submit</button>
    </form>
  );
}
  • Controlled field: the value lives in state. Ideal for live validation, transforming input, disabling a button, or clearing the form.
  • Uncontrolled field: the value lives in the browser. Sufficient for a very simple form where data is only read on submission.

In this course, we mainly use controlled fields because they fit naturally into the way React works. Just remember one rule: never usevalueanddefaultValueon the same field. You must choose one or the other.

Textarea and Dropdown Lists

These two elements are controlled like text fields, but their original HTML syntax is different, and React has simplified it. In HTML, the content of atextareais written between its tags, and the selected option of aselectuses theselectedattribute. In React, both simply usevalue.

controlled textarea and select
import { useState } from "react";

function Review() {
  const [comment, setComment] = useState("");
  const [rating, setRating] = useState("5");

  return (
    <form>
      <label htmlFor="rating">Rating</label>
      <select
        id="rating"
        value={rating}
        onChange={(e) => setRating(e.target.value)}
      >
        <option value="5">5 - Excellent</option>
        <option value="4">4 - Good</option>
        <option value="3">3 - Average</option>
      </select>

      <label htmlFor="comment">Comment</label>
      <textarea
        id="comment"
        value={comment}
        onChange={(e) => setComment(e.target.value)}
        rows={4}
      />

      <p>Rating: {rating} / 5, {comment.length} character(s)</p>
    </form>
  );
}

Notice that the value of aselectis always a string, even when the options look like numbers: the ratingstate contains"5"rather than5. If you need to perform calculations, convert it usingNumber(rating). The same applies to an input withtype="number".

Filtering What the User Can Type

Since you decide what enters the state, you can reject certain characters. Here is a phone number field that only keeps digits: any letter typed is simply ignored.

accepting digits only
import { useState } from "react";

function PhoneField() {
  const [phone, setPhone] = useState("");

  function handleChange(e) {
    // Remove anything that is not a digit
    const digits = e.target.value.replace(/[^0-9]/g, "");
    setPhone(digits);
  }

  return (
    <div>
      <label htmlFor="phone">Phone</label>
      <input id="phone" value={phone} onChange={handleChange} maxLength={10} />
    </div>
  );
}

The expression/[^0-9]/gmeans "any character that is not a digit", andreplacereplaces those characters with an empty string. This type of filtering can be implemented cleanly with a controlled field: the field always displays what is stored in state, so rejected characters never appear on the screen.

Submitting the Form

With onSubmiton the formelement, you handle submission yourself. Remember to calle.preventDefault()to prevent the page from reloading.

By default, an HTML form reloads the page when submitted, which would cause your application to lose its state. By callingpreventDefault, you cancel this behavior and stay in control: you can validate the data, send it to a server, and then display a confirmation message.

contact form
import { useState } from "react";

function Contact() {
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [sent, setSent] = useState(false);

  function handleSubmit(e) {
    e.preventDefault();
    console.log("Sent:", { email, message });
    setSent(true);
    setEmail("");
    setMessage("");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        placeholder="Your email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        required
      />
      <textarea
        placeholder="Your message"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        required
      />
      <button type="submit">Send</button>
      {sent && <p>Thank you, your message has been sent!</p>}
    </form>
  );
}

export default Contact;

Notice that the fields are cleared after submission simply by resetting their states to empty strings. This is one of the major benefits of controlled fields: no DOM manipulation is necessary.

Validating Before Submission

HTML attributes such asrequiredare useful, but we often want more precise rules and custom messages. We can store an error message in state and display it conditionally using conditional rendering:

simple validation
import { useState } from "react";

function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  function handleSubmit(e) {
    e.preventDefault();

    if (!email.includes("@")) {
      setError("The email must contain an @ symbol.");
      return;
    }

    if (password.length < 6) {
      setError("The password must contain at least 6 characters.");
      return;
    }

    setError("");
    console.log("Login successful");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Log in</button>
      {error && <p>{error}</p>}
    </form>
  );
}

One Error per Field

With a single error message, you can only report one problem at a time. To guide the user more precisely, we store an errors object: one key per field, with no error value when the field is valid.

an error message below each field
import { useState } from "react";

function Account() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errors, setErrors] = useState({});

  function validate() {
    const newErrors = {};

    if (!email.includes("@")) {
      newErrors.email = "The email must contain an @ symbol.";
    }
    if (password.length < 6) {
      newErrors.password = "At least 6 characters are required.";
    }

    return newErrors;
  }

  function handleSubmit(e) {
    e.preventDefault();
    const result = validate();
    setErrors(result);

    if (Object.keys(result).length === 0) {
      console.log("Valid form");
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      {errors.email && <p>{errors.email}</p>}

      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      {errors.password && <p>{errors.password}</p>}

      <button type="submit">Create account</button>
    </form>
  );
}

Thevalidatefunction builds an object containing only the errors found. If this object is empty, everything is valid. We check this usingObject.keys(result).length === 0. Separating validation from rendering makes the code easier to read, and you can add a new rule without changing the JSX.

Disabling the Button While the Form Is Incomplete

Since field values are stored in state, you can calculate whether the form is ready during each render and disable the submit button otherwise. There is no need for additional state: it is simply a calculated constant.

button disabled while the form is incomplete
function CommentForm() {
  const [author, setAuthor] = useState("");
  const [text, setText] = useState("");

  const ready = author.trim() !== "" && text.trim().length >= 10;

  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <input value={author} onChange={(e) => setAuthor(e.target.value)} />
      <textarea value={text} onChange={(e) => setText(e.target.value)} />
      <button type="submit" disabled={!ready}>
        Publish
      </button>
      {!ready && <p>Write at least 10 characters and enter your name.</p>}
    </form>
  );
}

Showing an Error Only After the Field Loses Focus

Live validation can display an error as soon as the first letter is typed, which can be frustrating because the user has not finished entering the value yet. TheonBlurevent, triggered when a field loses focus, lets you wait until that moment.

validate when leaving the field
function EmailField() {
  const [email, setEmail] = useState("");
  const [touched, setTouched] = useState(false);

  const invalid = touched && !email.includes("@");

  return (
    <div>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        onBlur={() => setTouched(true)}
      />
      {invalid && <p>Invalid email address.</p>}
    </div>
  );
}

Thetouchedstate becomestruewhen the user leaves the field for the first time. Before that, no error is displayed; afterward, the error updates live as the user types.

Managing Multiple Fields with a Single State

When a form contains many fields, you can group their values intoa single object and use each field'snameattribute to identify which one has changed:

Writing a separate useStateand function for every field quickly becomes repetitive. With one object and onehandleChangefunction, the code stays concise regardless of the number of fields. The brackets aroundname(computed property syntax) allow you to update the correct object key, while the spread operator (three dots) copies the other values so nothing is lost.

one state for the entire form
import { useState } from "react";

function Registration() {
  const [form, setForm] = useState({
    firstName: "",
    city: "",
    newsletter: false,
  });

  function handleChange(e) {
    const { name, value, type, checked } = e.target;
    setForm({
      ...form,
      [name]: type === "checkbox" ? checked : value,
    });
  }

  return (
    <form>
      <input name="firstName" value={form.firstName} onChange={handleChange} />
      <select name="city" value={form.city} onChange={handleChange}>
        <option value="">Choose a city</option>
        <option value="Antananarivo">Antananarivo</option>
        <option value="Toamasina">Toamasina</option>
        <option value="Mahajanga">Mahajanga</option>
      </select>
      <label>
        <input
          type="checkbox"
          name="newsletter"
          checked={form.newsletter}
          onChange={handleChange}
        />
        Receive the newsletter
      </label>
    </form>
  );
}
Screenshot of the completed registration form (first name, selected city, newsletter checkbox checked) with React Developer Tools showing the state.

Good to Know

For a checkbox, connect state to checked(not value). Also remember to connect eachlabelto its field usinghtmlFor: this improves accessibility.

Different Types of Fields

Not all fields are controlled in exactly the same way. Here is a summary of the main cases:

  • Text, email, password, textarea: usevalueand onChange.
  • Dropdown list: theselectelement receivesvalue, rather than an attribute on each option.
  • Checkbox: usecheckedand reade.target.checked.
  • Radio buttons: each button has its ownvalue, and checkedcompares the state with that value.
controlled radio buttons
import { useState } from "react";

function LevelSelection() {
  const [level, setLevel] = useState("beginner");

  return (
    <form>
      <label>
        <input
          type="radio"
          name="level"
          value="beginner"
          checked={level === "beginner"}
          onChange={(e) => setLevel(e.target.value)}
        />
        Beginner
      </label>
      <label>
        <input
          type="radio"
          name="level"
          value="advanced"
          checked={level === "advanced"}
          onChange={(e) => setLevel(e.target.value)}
        />
        Advanced
      </label>
      <p>Selected level: {level}</p>
    </form>
  );
}

Complete Example: A Registration Form

Let's bring together the concepts from this lesson: a single state object, different types of fields, validation on submission, a confirmation message, and resetting the form. First, read the entire code, then review each part.

complete registration
import { useState } from "react";

const INITIAL_VALUES = {
  firstName: "",
  email: "",
  level: "beginner",
  termsAccepted: false,
};

function CompleteRegistration() {
  const [form, setForm] = useState(INITIAL_VALUES);
  const [errors, setErrors] = useState({});
  const [confirmation, setConfirmation] = useState("");

  function handleChange(e) {
    const { name, value, type, checked } = e.target;
    setForm({
      ...form,
      [name]: type === "checkbox" ? checked : value,
    });
  }

  function validate() {
    const newErrors = {};
    if (form.firstName.trim() === "") {
      newErrors.firstName = "First name is required.";
    }
    if (!form.email.includes("@")) {
      newErrors.email = "The email is invalid.";
    }
    if (!form.termsAccepted) {
      newErrors.termsAccepted = "You must accept the terms.";
    }
    return newErrors;
  }

  function handleSubmit(e) {
    e.preventDefault();
    const result = validate();
    setErrors(result);

    if (Object.keys(result).length > 0) {
      setConfirmation("");
      return;
    }

    setConfirmation("Welcome " + form.firstName + "!");
    setForm(INITIAL_VALUES);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="firstName">First name</label>
      <input
        id="firstName"
        name="firstName"
        value={form.firstName}
        onChange={handleChange}
      />
      {errors.firstName && <p>{errors.firstName}</p>}

      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        value={form.email}
        onChange={handleChange}
      />
      {errors.email && <p>{errors.email}</p>}

      <label htmlFor="level">Level</label>
      <select
        id="level"
        name="level"
        value={form.level}
        onChange={handleChange}
      >
        <option value="beginner">Beginner</option>
        <option value="intermediate">Intermediate</option>
      </select>

      <label>
        <input
          type="checkbox"
          name="termsAccepted"
          checked={form.termsAccepted}
          onChange={handleChange}
        />
        I accept the terms
      </label>
      {errors.termsAccepted && <p>{errors.termsAccepted}</p>}

      <button type="submit">Register</button>
      {confirmation && <p>{confirmation}</p>}
    </form>
  );
}

export default CompleteRegistration;
  • Initial constant: the initial values are defined outside the component, allowing the form to be reset with a single call.
  • One handleChange function: thanks toname, it works for all fields, including the checkbox and dropdown list.
  • Separate validation: thevalidatefunction returns errors, andhandleSubmitdecides what happens next.
  • Resetting: after successful submission, the state is restored to its initial values and the form is cleared.

Accessible Forms

A well-built form should be usable by everyone, including people who navigate with a keyboard or a screen reader. React does not handle everything for you, but a few simple habits can make a big difference.

  • One label per field: connect it to the field usinghtmlForandid. Clicking the label then places the cursor in the field.
  • Do not replace the label with a placeholder: the example text disappears as soon as the user types, and some accessibility tools do not handle it well.
  • Clearly indicate errors: a written message near the field is more useful than a simple red border, which may not be visible to everyone.
  • Use real buttons: abuttonwithtype="submit"allows form submission using the Enter key without additional code.
an accessible field with its error message
<label htmlFor="email">Email address</label>
<input
  id="email"
  type="email"
  value={email}
  onChange={(e) => setEmail(e.target.value)}
  aria-invalid={error !== ""}
  aria-describedby="email-error"
/>
{error && <p id="email-error">{error}</p>}

Thearia-invalidattribute tells screen readers that the value is incorrect, whilearia-describedbyconnects the field to its error message, which can be read along with the field. These attributes keep their hyphenated syntax in JSX.

Common Mistakes

  • Forgetting preventDefault: the page reloads on submission and the state is lost.
  • Initializing state with undefined: React switches from an uncontrolled field to a controlled field and displays a warning. Always start with an empty string, a boolean, or a specific value.
  • Using value for a checkbox: usechecked.
  • Modifying the state object directly: always create a new object using the spread operator. Do not writeform.firstName = ....
  • Forgetting the name attribute: when using a single state object, withoutname, your function does not know which key to update.
  • Forgetting to convert text into a number: a field's value is always a string; useNumber(...)before performing calculations.
  • Placing a button without a type inside a form: it submits the form. Addtype="button"for an action that should not submit the form.

Key Takeaways

  • A controlled field stores its value in React state.
  • Connect the field to state usingvalue(orchecked) andonChange.
  • Handle submission withonSubmitande.preventDefault().
  • For multiple fields, a single objectand thenameattribute help avoid repetition.

Exercise

Create a login form with an email address and password. On submission, check that both fields are filled in and display an error message if they are not.

Go Further

Add a "Show password" checkbox that switches the field type betweenpasswordandtext.
suggested solution for exercise 1
import { useState } from "react";

function LoginExercise() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  function handleSubmit(e) {
    e.preventDefault();

    if (email.trim() === "" || password === "") {
      setError("All fields are required.");
      return;
    }

    setError("");
    console.log("Logging in:", email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Log in</button>
      {error && <p>{error}</p>}
    </form>
  );
}
suggested solution for Go Further
const [visible, setVisible] = useState(false);

// Inside the JSX
<input
  type={visible ? "text" : "password"}
  value={password}
  onChange={(e) => setPassword(e.target.value)}
/>

<label>
  <input
    type="checkbox"
    checked={visible}
    onChange={(e) => setVisible(e.target.checked)}
  />
  Show password
</label>

True or False?

  • A field with value but without onChange remains editable.
  • For a checkbox, we read e.target.checked.
  • The value of a select is always a number when the options contain numbers.
  • We can use value and defaultValue together on the same field.

Answers: False (it becomes read-only); True; False (it is still a string); False (you must choose one or the other).

Quick Glossary

  • Controlled field: a field whose value is managed by state.
  • Uncontrolled field: a field whose value is managed by the browser.
  • Source of truth: the single place where data is stored, in this case state.
  • Computed property: the [name] syntax that uses a variable as a property key.