Forms and Controlled Inputs

View saved

Controlled input pattern

Bind value to state and update it in onChange.

function SignupForm() {
  const [email, setEmail] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    console.log("Email:", email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </label>
      <button type="submit">Sign up</button>
    </form>
  );
}

Multiple fields

Use one state object or separate useState calls—start simple with separate calls.

const [name, setName] = useState("");
const [email, setEmail] = useState("");

Checkboxes and selects

Checkboxes use checked; selects still use value + onChange.

<input
  type="checkbox"
  checked={agree}
  onChange={(e) => setAgree(e.target.checked)}
/>

Validate before submit

Check required fields in handleSubmit and set an error message in state when something is missing.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.