Sikau

React · Day 9 · about 30 min

Forms and controlled inputs

Read and validate what people type.

Know what's typed, always

Live validation, character counters, a Submit button that enables only when the form is valid — all easy when the input's value lives in state. That's a controlled input.

value + onChange, onSubmit

import { useState } from "react";

export default function Signup() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const valid = email.includes("@");

  function handleSubmit(e) {
    e.preventDefault();
    setSent(true);
  }

  if (sent) return <p>Thanks! We'll write to {email}.</p>;

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email</label>
      <input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      {!valid && email && <p role="alert">Add an @</p>}
      <button disabled={!valid}>Sign up</button>
    </form>
  );
}
  • Checkboxes use checked={on} and e.target.checked.
  • <select value={…} onChange={…}> works the same way as inputs.
  • Several fields? Keep one object in state: setForm({ ...form, [e.target.name]: e.target.value }).

The rest of this lesson

  • Many fields, one objectexplain
  • Validation and feedbackexplain
  • What happens?predict
  • A controlled inputfill
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React