New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› React› Forms in React

Forms in React

💻 React

Build controlled forms, validate input and handle submission.

Lesson 5 of 9 Tutorial
0 of 9 completed

Forms are where users do real work. React keeps every field in state so you can validate before sending anything.

By the end of this lesson you can:
  • Build a controlled form.
  • Validate fields.
  • Reset after submit.

One State Object

For a form with several fields, one object is easier to manage than many separate state values.

import { useState } from "react";

function Signup() {
  const [form, setForm] = useState({ name: "", email: "" });

  function handleChange(event) {
    const { name, value } = event.target;
    setForm(current => ({ ...current, [name]: value }));
  }

  return (
    <form>
      <input name="name" value={form.name} />
      <input name="email" value={form.email} />
    </form>
  );
}

Validation

Validate on submit for the first version. Show field errors next to the field and keep the values so the user does not retype everything.

function validate(form) {
  const errors = {};

  if (form.name.trim().length < 2) errors.name = "Enter at least 2 characters.";
  if (!form.email.includes("@")) errors.email = "Enter a valid email.";

  return errors;
}

Submit

Prevent the default page reload, validate, then send the data. Disable the button while the request is running to prevent double submits.

Tip Give every input a label and an id. It makes the form usable with a screen reader and easier to test.

Practice

  1. Add a password field with a minimum length rule.
  2. Show field errors under each input.
  3. Reset the form after a successful submit.

Hands-on exercise

Build a contact form with name, email and message.
1. Keep all values in one state object.
2. Validate on submit.
3. Show errors under the fields.
4. Clear the form on success.

Recap

Controlled inputs keep form state in React. Validate on submit, show helpful errors and reset deliberately.

Example

import { useState } from "react";

function Signup() {
  const [form, setForm] = useState({ name: "", email: "" });

  function handleChange(event) {
    const { name, value } = event.target;
    setForm(current => ({ ...current, [name]: value }));
  }

  return (
    <form>
      <input name="name" value={form.name} onChange={handleChange} />
      <input name="email" value={form.email} onChange={handleChange} />
    </form>
  );
}

Exercises

Exercise 1. Contact form Medium
Build a contact form with name, email and message.
1. Keep all values in one state object.
2. Validate on submit.
3. Show errors under the fields.
4. Clear the form on success.
React exercise-1.txt
Expected Output
A validated form that clears after a successful submit.

Lesson Nav

Lesson sections