Controlled Components in React: Forms Tutorial with Examples

Learn the state, value and onChange loop by building a name preview and a complete course-interest form with exact validation outcomes.

KnowledgeGate Team

Exam prep & CS education

Updated 4 Dec 20265 min read
Controlled Components in React: Forms Tutorial with Examples

An <input> can render yet freeze, reset or diverge from state. Build a controlled input, a course-interest form, exact validation outcomes, repairs and exercises. For a structured path, use the React and Redux course.

1. What makes a React form control controlled

State holds a controlled input's value, value or checked displays it, onChange updates state, and React renders again. The official React input reference requires this update to be synchronous.

Start with name = ''. Type A: event.target.value is 'A', setName('A') schedules an update, and the next render supplies value="A". Finish typing, and state and input contain 'Asha'. State is the source of truth.

value controls every render; defaultValue="Asha" only sets an uncontrolled input initially. Apply this across coding and skill-development paths.

Clockwise five-step React controlled-input loop showing the name changing from empty to Asha as typing updates state and the visible input value.

2. Build the smallest runnable controlled input

jsx
import { useState } from 'react';

export default function NamePreview() {
  const [name, setName] = useState('');

  return (
    <section>
      <label htmlFor="name">Name</label>
      <input
        id="name"
        value={name}
        onChange={event => setName(event.target.value)}
      />
      <p>Hello, {name || 'learner'}!</p>
    </section>
  );
}

Initially, useState('') supplies a string and shows Hello, learner!. Type Asha: state is 'Asha' and the paragraph says Hello, Asha!. Delete four characters, and '' restores Hello, learner!.

The handler copies the DOM value into state. With only <input value={name} />, typing cannot change the display. Two-way binding still has explicit event and render steps.

3. Control a complete form with one state object

jsx
import { useState } from 'react';

const initialForm = {
  fullName: '', email: '', track: 'react', notes: '', agree: false
};

export default function CourseInterestForm() {
  const [form, setForm] = useState(initialForm);

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

  return (
    <form>
      <input name="fullName" value={form.fullName} onChange={handleChange} />
      <input name="email" type="email" value={form.email} onChange={handleChange} />
      <select name="track" value={form.track} onChange={handleChange}>
        <option value="react">React</option>
        <option value="javascript">JavaScript</option>
      </select>
      <textarea name="notes" value={form.notes} onChange={handleChange} />
      <label>
        <input name="agree" type="checkbox" checked={form.agree} onChange={handleChange} />
        I agree to submit this form
      </label>
      <pre>{JSON.stringify(form, null, 2)}</pre>
    </form>
  );
}

Enter Asha Jain, asha@example.com and Build a quiz app, keep track as react, and tick the box. The rendered JSON is { "fullName": "Asha Jain", "email": "asha@example.com", "track": "react", "notes": "Build a quiz app", "agree": true }.

The functional updater reads current state; the spread keeps siblings. Returning only { [name]: value } for email loses four keys. Review HTML form elements and attributes if needed.

React puts a controlled select value on <select>, not its option. A controlled textarea uses value, not child text.

4. Handle checkboxes, radio buttons and numeric inputs deliberately

For a checkbox, event.target.value is commonly 'on'; event.target.checked is boolean. React controls checkboxes and radios through checked. Ticking agree must store true.

jsx
const [plan, setPlan] = useState({
  mode: 'self-paced', hoursPerWeek: '6', emailUpdates: false
});

function handlePlanChange(event) {
  const { name, type, value, checked } = event.target;
  setPlan(previous => ({
    ...previous,
    [name]: type === 'checkbox' ? checked : value
  }));
}

<input type="radio" name="mode" value="self-paced"
  checked={plan.mode === 'self-paced'} onChange={handlePlanChange} />
<input type="radio" name="mode" value="guided"
  checked={plan.mode === 'guided'} onChange={handlePlanChange} />
<input type="number" name="hoursPerWeek"
  value={plan.hoursPerWeek} onChange={handlePlanChange} />
<input type="checkbox" name="emailUpdates"
  checked={plan.emailUpdates} onChange={handlePlanChange} />

Choose guided, replace 6 with 8, and tick updates. State is { mode: 'guided', hoursPerWeek: '8', emailUpdates: true }. Number inputs report strings. Preserve '', reject blanks, then convert. Number('8') is 8; Number('') is 0 and could create false data.

5. Validate and submit the exact form state

Add errors state, then validate before creating a result:

jsx
const [errors, setErrors] = useState({});

function validate(values) {
  const next = {};
  if (values.fullName.trim().length < 3)
    next.fullName = 'Enter at least 3 characters';
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email))
    next.email = 'Enter a valid email';
  if (values.agree !== true)
    next.agree = 'You must agree before submitting';
  return next;
}

function handleSubmit(event) {
  event.preventDefault();
  const nextErrors = validate(form);
  setErrors(nextErrors);
  if (Object.keys(nextErrors).length > 0) return;
  const payload = { ...form };
  console.log(payload);
}

Wire it through <form onSubmit={handleSubmit}>, show errors.fullName, errors.email and errors.agree beside their controls, and use <button type="submit">Submit</button>.

For { fullName: ' AJ ', email: 'asha.example.com', track: 'react', notes: '', agree: false }, trimming gives AJ, length 2. Errors are { fullName: 'Enter at least 3 characters', email: 'Enter a valid email', agree: 'You must agree before submitting' }. preventDefault() stops navigation; no payload is produced.

Correct to { fullName: 'Asha Jain', email: 'asha@example.com', track: 'react', notes: 'Build a quiz app', agree: true }. Zero errors produce that payload. Logging is client-side only. Study Mongoose schemas, models, validation and population before persistence.

Two-row course-interest form validation flow showing invalid AJ and malformed email errors above corrected Asha Jain data, a five-field payload, and client-side status.

6. Keep one owner for each input from the first render

Live validation, conditional UI and shared values need the current value in React state, so every field in CourseInterestForm stays controlled. React Forms: Controlled vs Uncontrolled Components compares state ownership, shows a ref-based uncontrolled example and covers the interview angle; the course-interest form here instead traces multiple fields, exact submit results and validation.

With useState(), undefined makes email uncontrolled; setting 'asha@example.com' then controls it. Use useState('') and keep a string, following React's no-switch and non-null guidance.

7. Diagnose the common controlled-form failures

Failure

Outcome

Repair

<input value="Asha" />

Meera cannot replace the fixed value

Add state and synchronous onChange, or use defaultValue="Asha"

form.email = 'asha@example.com'; setForm(form);

Mutates and reuses one object

Use setForm(previous => ({ ...previous, email: 'asha@example.com' }))

setForm({ email: 'asha@example.com' })

Keeps only email

Spread previous state first

setForm(previous => ({ ...previous, agree: event.target.value }))

Stores 'on'

Read event.target.checked to store true

Form button has no type

Reset or Preview may submit

Use type="button"; reserve type="submit" for submit

React requires synchronous updates. Delaying setName(nextValue) by 100 milliseconds, or substituting another string in that callback, can revert the field and move the caret.

Check the initial type, handler, value or checked, then other keys.

8. Exercises, the short version and the next study action

Try these before reading the answers:

  1. Start city at 'Jaipur', control one text input, then type Pune.

  2. Add beginner and intermediate radios to { level: 'beginner' }, then select the second.

  3. Validate hoursPerWeek for '' and '6'.


  1. Input and state both contain 'Pune'; {city} renders Pune.

  2. State is { level: 'intermediate' }; only that radio has checked={true}.

  3. For '', show Enter weekly hours and do not call Number. For '6', validation passes and the payload stores the number 6.

Keep this six-line recall card:

  • Initialise controlled values with the correct type.

  • Render value or checked.

  • Update from onChange.

  • Preserve sibling fields in object state.

  • Validate before producing a payload.

  • Never switch a field between controlled and uncontrolled.

Continue through the Web Development pillar. Type NamePreview, rebuild CourseInterestForm from memory, and submit the exact Asha Jain payload. Use the course above for React, or the MERN Stack full-stack development course for full-stack projects.