SkillPilotAI

Forms in React

Forms in React come in two styles: controlled inputs, where React state drives the value and onChange updates it, and uncontrolled inputs, where the DOM keeps the value and you read it on submit (FormData). Knowing both, plus preventDefault and validation, covers almost every form you will build.

30.1 The problem: the input is locked

  • name state starts as "" and the input has value={name}.
  • Typing "Rahul" shows nothing, as if the input were locked.
  • Console: You provided a `value` prop to a form field without an `onChange` handler.
React (JSX)
import { useState } from "react"; function Signup() {  const [name, setName] = useState("");  return (    <form>      <input        value={name}        placeholder="Name"      />      <p>Hello, {name}</p>    </form>  );}
Output
-- after typing "Rahul" --[ Name ]Hello,Console: You provided a `value` prop to a form field without an `onChange` handler.

30.2 Why the input is locked

  • With a value prop, React promises the input always shows exactly what is in state.
  • A key press adds a letter in the browser, but state is still "", so React resets the input.
  • Nobody called setName. An input fully driven by state is a controlled input.

30.3 Fix: value + onChange

  • onChange runs on every key press.
  • setName(e.target.value) puts what was typed into state.
  • React re-renders and the new name shows in both the input and the paragraph: Hello, Rahul live.
React (JSX)
import { useState } from "react"; function Signup() {  const [name, setName] = useState("");  return (    <form>      <input        value={name}        onChange={(e) => setName(e.target.value)}        placeholder="Name"      />      <p>Hello, {name}</p>    </form>  );}
Output
-- start --[ Name ]Hello,-- after typing "Rahul" --[ Rahul ]Hello, Rahul
Controlled input cycle
  1. 1.User presses a key

  2. 2.onChange fires with the event

  3. 3.setName(e.target.value) updates state

  4. 4.React re-renders the component

  5. 5.Input value and Hello text show the new state

React state is the single source of truth

30.4 Many inputs, one handler

  • Keep all fields in one object state: { name: "", email: "" }.
  • Give every input a name attribute matching the key.
  • handleChange reads { name, value } from e.target.
  • { ...form, [name]: value } copies the old object and updates only that key (computed key).
React (JSX)
const [form, setForm] = useState({  name: "", email: "",});function handleChange(e) {  const { name, value } = e.target;  setForm({ ...form, [name]: value });}return (  <form>    <input name="name" value={form.name}      onChange={handleChange} />    <input name="email" value={form.email}      onChange={handleChange} />  </form>);
Output
[ Rahul ][ rahul@gmail.com ]

30.5 Submit and validation

  • e.preventDefault() stops the browser's default full-page reload on submit (which would lose all state).
  • Simple validation: no @ in the email sets an error and returns early.
  • A valid email clears the error and saves the data.
  • {error && <p>{error}</p>} shows the error only when it is not empty.
  • Both the button click and the Enter key trigger onSubmit.
React (JSX)
function handleSubmit(e) {  e.preventDefault();  if (!form.email.includes("@")) {    setError("Enter a valid email");    return;  }  setError("");  console.log("Saved:", form);} <form onSubmit={handleSubmit}>  {/* name + email inputs */}  {error && <p>{error}</p>}  <button>Sign up</button></form>
Output
-- email "rahul", submit --[ Rahul ][ rahul ]Enter a valid email[button] Sign up -- email "rahul@gmail.com", submit --[ Rahul ][ rahul@gmail.com ][button] Sign upConsole: Saved: {name: 'Rahul', email: 'rahul@gmail.com'}
Submit flow
  1. 1.User clicks Sign up or presses Enter

  2. 2.onSubmit runs handleSubmit

  3. 3.e.preventDefault(): no page reload

  4. 4.Validate: email has no @? setError and return

  5. 5.Valid: clear the error and save / send the data

30.6 Uncontrolled inputs with FormData

  • The value lives in the DOM, not React state; no useState at all.
  • defaultValue sets only the starting value.
  • new FormData(e.currentTarget) reads every named input at once; Object.fromEntries turns it into a plain object.
React (JSX)
function handleSubmit(e) {  e.preventDefault();  const data = new FormData(e.currentTarget);  console.log(Object.fromEntries(data));} function Feedback() {  return (    <form onSubmit={handleSubmit}>      <input name="name" defaultValue="Raj" />      <input name="rating" type="number" />      <button>Send</button>    </form>  );}
Output
{name: 'Raj', rating: '5'}

Checkpoint: rating is "4" and rating + 1 logs 41, not 5. Every form value is a string, even with type="number"; convert with Number() first.

React (JSX)
function handleSubmit(e) {  e.preventDefault();  const data = new FormData(e.currentTarget);  const rating = data.get("rating");  console.log(rating + 1);}
Output
41Screen: Number(rating) + 1 gives 5

30.7 Comparison: controlled vs uncontrolled

PointControlledUncontrolled
Value lives inReact stateThe DOM
Set withvalue + onChangedefaultValue
Read withState, any timeFormData or a ref, on submit
Good forLive validation, search suggestions, disabling a buttonSimple forms, data needed only on submit
CodeMore (state + handler)Shorter
File inputNot possibleAlways uncontrolled (value cannot be set from code)

30.8 Common mistakes

  • value without onChange: the input becomes read-only.
  • useState() with no initial value: value is undefined (uncontrolled), then becomes a string, and React warns a component is changing an uncontrolled input to be controlled. Start with "".
  • Forgetting preventDefault: the page reloads on submit.
  • Doing math on form values without Number().
  • Myth: every input needs its own useState. Both styles are official; React 19's form action prop also gives you FormData directly.
React (JSX)
// Wrong: warning, uncontrolled to controlledfunction City() {  const [city, setCity] = useState();  return (    <input      value={city}      onChange={(e) => setCity(e.target.value)}    />  );}
React (JSX)
// Right: controlled from the first renderfunction City() {  const [city, setCity] = useState("");  return (    <input      value={city}      onChange={(e) => setCity(e.target.value)}    />  );}

30.9 Rules for forms

  1. Controlled input: value + onChange, initial value "".
  2. Checkbox: use checked and e.target.checked, not value.
  3. Give every input a name attribute; connect labels with htmlFor.
  4. preventDefault on submit, and always validate again on the server.

30.10 Interview tips

  • Controlled: value comes from React state and onChange updates it; React is the single source of truth.
  • Uncontrolled: the DOM keeps the value; start with defaultValue and read it on submit via a ref or FormData.
  • Controlled suits live validation; uncontrolled suits simple forms.
  • Form values are always strings; convert before calculating.
  • Browser validation can be bypassed, so validate on the server too.