Thuta Learning
BasicWeb Developmentintermediate

Forms & Inputs

Relax. We'll talk through this in plain words — no textbook voice.

When you wire an input's value to state in a React form, your component always knows what the user is typing. This pattern is called a controlled component, and it's widely used for search boxes, contact forms, signup forms, and settings forms.

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>
  );
}

Every time the user types, `onChange` fires and updates the `name` state. When Submit is clicked, `handleSubmit` grabs the name from state and shows it in an alert.

You should see
Type a name into the input and hit Send — a `Hello [name]` alert pops up.

Info

In a controlled input, the UI value and the React state always stay in sync. That makes validation, previews, and search filtering all much easier to build.

Easy traps

  • If you set `value` but forget `onChange`, the input can end up stuck as read-only.