Thuta Learning
React
BasicWeb DevelopmentIntermediate

Forms & Inputs

ReactLesson 1130 min

What you'll walk away with

  • Write controlled inputs with value + onChange, starting from an initial value of ''
  • Explain how an uncontrolled form with defaultValue and FormData differs
  • Handle checkboxes (checked), selects, textareas and many fields with one name-based handler
  • Call preventDefault() in onSubmit and derive validation errors from state during render

Explain it simply

Explain it simply

Think of filling in a form at a bank counter. In one style, the clerk watches every letter you write and points out mistakes immediately. In the other, you fill in the whole form and hand it over, and the clerk checks it all at once.

In React the first style is a controlled input: every keystroke lands in state, so the component always knows what the user is typing. The second is an uncontrolled input: the browser holds the value and you read it on submit. Both are valid; the skill is choosing the right one.

Problem → Why → Solution

The problem: a frozen input and a console warning

The signup form below has two problems. No matter how much you type into the email field, not a single character appears. The nickname field accepts typing, but on the first keystroke the console shows "A component is changing an uncontrolled input to be controlled."

SignupForm.jsx
import { useState } from 'react';

function SignupForm() {
  const [email, setEmail] = useState('');
  const [nickname, setNickname] = useState(); // undefined at first

  return (
    <form>
      {/* Bug 1: value but no onChange, so the field is frozen */}
      <input type="email" value={email} />

      {/* Bug 2: value starts as undefined (uncontrolled), then a string */}
      <input value={nickname} onChange={(e) => setNickname(e.target.value)} />
    </form>
  );
}

Why does this happen?

As soon as you pass a value prop, React pins the input to that value. Without an onChange that updates the state, the value stays '' forever and the input is frozen. value={undefined}, on the other hand, means "no value given" to React, so the input starts uncontrolled and becomes controlled once it gets a string. An input must stay one kind for its whole life.

Core concept: who owns the value?

In a controlled input, React state is the source of truth for the value. With <input value={name} onChange={e => setName(e.target.value)} />, every key press runs onChange, updates state, re-renders the component, and the input shows the new value. React's onChange fires on every keystroke, not only when focus leaves the field like the browser's native change event. Because the value is in state, live previews, character counters, search filters and forcing input to uppercase are all easy.

Controlled inputs come with a few rules. Start from '' rather than undefined or null. e.target.value is always a string, even for type="number", so convert it with Number() before doing arithmetic. For a checkbox, use checked={agree} and e.target.checked instead of value. For <select>, put the value on the select itself, <select value={size}>, rather than marking an option as selected, and <textarea> takes its text through the value prop rather than children.

With many fields you do not need one piece of state per field. Give each input a name attribute, keep the values in one state object, and let a single handler update it with setValues(prev => ({ ...prev, [e.target.name]: e.target.value })).

In an uncontrolled input, the DOM keeps the value. You give a starting value with defaultValue (defaultChecked for checkboxes) and read the values by name on submit with new FormData(event.currentTarget). There is no re-render on every keystroke, so simple forms need less code. React 19 also lets you pass a function as <form action={fn}>, which receives the FormData directly; the Actions lesson covers that in detail.

Handle sending in the form's onSubmit, not in the button's onClick, so that pressing Enter inside an input submits too. Call event.preventDefault() on the first line of the handler to stop the page from reloading.

Mental model: the controlled input loop
  1. The user presses a key
  2. onChange reads e.target.value
  3. setState stores the new value
  4. Re-render: the input shows state

Break any link in the loop, such as a missing onChange, and the input freezes.

General pattern

jsx
const [value, setValue] = useState('');          // never undefined

<form onSubmit={(e) => { e.preventDefault(); /* use value */ }}>
  <input value={value} onChange={(e) => setValue(e.target.value)} />
  <input type="checkbox" checked={flag} onChange={(e) => setFlag(e.target.checked)} />
  <select value={choice} onChange={(e) => setChoice(e.target.value)}>...</select>
  <button type="submit">Send</button>
</form>

// Uncontrolled alternative: <input name="field" defaultValue="" />
// and on submit: new FormData(e.currentTarget).get('field')

Every controlled field needs both value (checked for checkboxes) and onChange. Handle submit in the form's onSubmit and call preventDefault(). An uncontrolled field gets defaultValue and a name, and you read it with FormData.

Example: a contact form with one controlled input

The name state drives the input's value, and onChange updates that state on every keystroke. On submit, the handler does not read the DOM at all; it uses name straight from state.

jsx
import { useState } from 'react';

function ContactForm() {
  const [name, setName] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    alert('Hello ' + name);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Your name
        <input
          value={name}
          onChange={event => setName(event.target.value)}
        />
      </label>
      <button type="submit">Send</button>
    </form>
  );
}

Code breakdown

  1. Line 4const [name, setName] = useState('');

    Starting from '' makes the input controlled from the very first render. useState() would trigger the uncontrolled-to-controlled warning.

  2. Line 7event.preventDefault();

    Stops the browser's default submit, which reloads the page. Without it, the page would reload right after the alert and the state would be lost.

  3. Line 16value={name}

    The input shows only what is in state, which also means calling setName('') would clear it from code.

  4. Line 17onChange={event => setName(event.target.value)}

    Each keystroke copies the input's current text into state. Without this line, value={name} would lock the input at ''.

  5. Line 20<button type="submit">Send</button>

    The submit button triggers the form's onSubmit, and so does pressing Enter inside the input.

You should see
A text input labelled "Your name" and a Send button render. Type Aye and click Send (or press Enter): an alert reads "Hello Aye" and the page does not reload.

Controlled vs uncontrolled at a glance

ControlledUncontrolled
Where the value livesReact stateThe DOM (browser)
Propsvalue + onChangedefaultValue + name
When you can read itOn every renderOn submit (FormData)
Best forLive validation, previews, filtersSimple forms, file inputs

An <input type="file"> cannot be controlled: for security reasons, the browser does not let code set its value. File inputs are therefore always uncontrolled, and you read them from FormData or e.target.files.

FeedbackForm.jsx
export default function FeedbackForm() {
  function handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    console.log(data.get('rating'), data.get('comment'));
  }

  return (
    <form onSubmit={handleSubmit}>
      <select name="rating" defaultValue="5">
        <option value="5">Great</option>
        <option value="3">Okay</option>
      </select>
      <textarea name="comment" defaultValue="" />
      <button type="submit">Send feedback</button>
    </form>
  );
}

In real projects

Where this shows up in real projects

Search boxes are the classic controlled input: each keystroke filters a list and often writes the query into the URL. For long forms with many rules, such as checkout or signup, many teams use a library like React Hook Form with a Zod schema for validation. Those libraries use uncontrolled inputs and refs under the hood, so the whole form does not re-render on every keystroke.

Whichever approach you use, validation in the browser exists to help the user; the server must check the data again. Wrapping inputs in a <label> or linking them with htmlFor, and connecting error messages through aria-describedby, are essential for screen reader users. Disabling the submit button while the request is in flight prevents double submissions.

Common mistakes

Common mistakes

1. value without onChange

The input becomes read-only and React warns "You provided a `value` prop to a form field without an `onChange` handler". Add onChange, write readOnly if that was intended, or use defaultValue for an uncontrolled field.

2. Treating e.target.value as a number

Type 20 into a type="number" input and age + 1 gives "201", not 21, because the value is a string. Convert with Number(e.target.value) before storing or computing, and remember that Number('') is 0 for an empty field.

3. Updating object state without spreading it

setValues({ [e.target.name]: e.target.value }) drops every other field from state, which turns them into undefined and brings back the uncontrolled warning. Always copy: { ...prev, [name]: value }.

Best practices

Best practices

  • If no field needs live feedback such as a preview or a filter, an uncontrolled form with FormData is simpler.
  • Show an error only after the user leaves the field (onBlur) or tries to submit once; do not greet them with red messages before they have typed anything.
  • Keep validation rules in a pure function such as validate(), so they can be tested without the component and reused on the server.
  • Give every input a visible label; a placeholder is not a replacement for one.

Mini challenge

Mini challenge: a signup form with validation

Write a controlled signup form with email, password and a terms checkbox. Compute errors from state during render and allow submit only when the form is valid.

  • One values state object ({ email, password, agree }) and a single name-based handleChange
  • A pure validate(values) returns an error object { email?, password?, agree? }
  • The submit button stays disabled while errors exist, and each error shows under its field
  • A successful submit shows Welcome, <email>!
SignupForm.jsx
import { useState } from 'react';

export function validate(values) {
  const errors = {};
  // TODO: email must contain '@'          -> 'Enter a valid email.'
  // TODO: password needs 8+ characters    -> 'Use at least 8 characters.'
  // TODO: agree must be true              -> 'Please accept the terms.'
  return errors;
}

export default function SignupForm() {
  // TODO: values state { email: '', password: '', agree: false }
  // TODO: submitted state
  // TODO: errors = validate(values); isValid when there are no errors

  function handleChange(event) {
    // TODO: use event.target.name; checkboxes use event.target.checked
  }

  function handleSubmit(event) {
    // TODO: stop the reload, then mark as submitted if valid
  }

  // TODO: after submit show <p>Welcome, {email}!</p>, otherwise the form
}

Expected: At first: all three errors show and the Create account button is disabled. validate({ email: 'aye@example.com', password: 'secret123', agree: true }) returns {}. Fill in those values and submit: Welcome, aye@example.com!

Show hint

In handleChange, destructure const { name, type, value, checked } = event.target; and pick type === 'checkbox' ? checked : value. Do not keep errors in state; compute them with validate(values) on every render. This exercise shows errors right away; a real form should wait for blur or the first submit, as the best practices suggest.

Show solution
SignupForm.jsx
import { useState } from 'react';

export function validate({ email, password, agree }) {
  const errors = {};
  if (!email.includes('@')) errors.email = 'Enter a valid email.';
  if (password.length < 8) errors.password = 'Use at least 8 characters.';
  if (!agree) errors.agree = 'Please accept the terms.';
  return errors;
}

export default function SignupForm() {
  const [values, setValues] = useState({ email: '', password: '', agree: false });
  const [submitted, setSubmitted] = useState(false);
  const errors = validate(values);
  const isValid = Object.keys(errors).length === 0;

  function handleChange(event) {
    const { name, type, value, checked } = event.target;
    setValues((prev) => ({ ...prev, [name]: type === 'checkbox' ? checked : value }));
  }

  function handleSubmit(event) {
    event.preventDefault();
    if (isValid) setSubmitted(true);
  }

  if (submitted) return <p>Welcome, {values.email}!</p>;

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label>
        Email
        <input name="email" type="email" value={values.email} onChange={handleChange} />
      </label>
      {errors.email && <p className="error">{errors.email}</p>}
      <label>
        Password
        <input name="password" type="password" value={values.password}
          onChange={handleChange} />
      </label>
      {errors.password && <p className="error">{errors.password}</p>}
      <label>
        <input name="agree" type="checkbox" checked={values.agree}
          onChange={handleChange} />
        I accept the terms
      </label>
      {errors.agree && <p className="error">{errors.agree}</p>}
      <button type="submit" disabled={!isValid}>Create account</button>
    </form>
  );
}

Quick quiz 1 / 3

With const [city] = useState('Yangon'); and <input value={city} /> with no onChange, what happens when the user types?

Quick quiz 2 / 3

Which initial state avoids the "uncontrolled to controlled" warning for a text input?

Quick quiz 3 / 3

A number input has const [age, setAge] = useState(0); and onChange={e => setAge(e.target.value)}. After typing 20, what is age + 1?

What to remember

  • In a controlled input, state is the source of truth: it needs value + onChange and should start from ''.
  • In an uncontrolled input, the DOM keeps the value: start it with defaultValue and read it with FormData on submit.
  • Checkboxes use checked and e.target.checked, selects and textareas take a value prop, and e.target.value is always a string.
  • Call preventDefault() in <form onSubmit>, derive errors from state during render, and validate again on the server.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Forms & Inputs | Thuta Learning