mediumFrontend

How do you handle forms in React?

640 views
01

Understand the problem

Discuss common strategies for managing form input, state, and submissions in React applications.

formsstate managementeventscontrolled components
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Controlled form with one change handler
import { useState } from "react";

export default function App() {
  const [form, setForm] = useState({ name: "", email: "" });
  const onChange = (e) =>
    setForm((f) => ({ ...f, [e.target.name]: e.target.value })); // key by name

  const onSubmit = (e) => {
    e.preventDefault();                       // stop the page reload
    if (!form.email.includes("@")) return alert("invalid email");
    alert("submitted: " + JSON.stringify(form));
  };

  return (
    <form onSubmit={onSubmit} style={{ padding: 24, fontFamily: "system-ui" }}>
      <input name="name" value={form.name} onChange={onChange} placeholder="name" />
      <input name="email" value={form.email} onChange={onChange} placeholder="email" />
      <button type="submit">Send</button>
    </form>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.