MyInternships.in

State & Events

React Forms and Controlled Components

A controlled component is a form input whose value comes from React state and whose onChange handler writes back to that state. React becomes the single source of truth for what the field contains.


What is Forms and Controlled Components in React?

A controlled component is a form input whose value comes from React state and whose onChange handler writes back to that state. React becomes the single source of truth for what the field contains.

Why Forms and Controlled Components matters

Once the value lives in state you can validate as the user types, disable the submit button, format input, reset the form, and prefill it from an API — all with ordinary state logic.

Forms and Controlled Components example

A controlled input
JSX
function EmailField() {
  const [email, setEmail] = useState('');
  const valid = /\S+@\S+\.\S+/.test(email);

  return (
    <>
      <input
        type="email"
        value={email}
        onChange={e => setEmail(e.target.value)}
      />
      {!valid && email && <small>Enter a valid email</small>}
      <button disabled={!valid}>Continue</button>
    </>
  );
}

How this works

value={email} forces the input to display state, and onChange pushes each keystroke back into state. The two together form the controlled loop; remove either one and the field stops working as expected.

Key points to remember

  • Always pair value with onChange, or React warns about a read-only field.
  • Checkboxes use checked instead of value, and read e.target.checked.
  • Use value={x ?? ''} so an undefined value does not flip the input to uncontrolled.
  • <select> takes value on the select element itself, not selected on options.

Common mistakes with Forms and Controlled Components

  • Setting value without onChange, which makes the field impossible to type in.
  • Starting with value={undefined} and later setting a string — React warns that a component is changing from uncontrolled to controlled.
  • Storing every field in its own useState when one object or useReducer would be tidier.

React Forms and Controlled Components— Interview Questions & FAQs

Why can I not type in my React input?+

You set value from state but did not attach an onChange handler, so state never updates and React re-renders the same value. Add onChange={e => setValue(e.target.value)}.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships