Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

Forms and Controlled Components

Forms and Controlled Components

In plain HTML, an input manages its own value. In React, the "controlled component" pattern is used instead — the input's value always comes from React state, and every keystroke updates that state. This keeps a form's entire data in one place (state).

Single Input Example

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

  return (
    <input
      type="text"
      value={name}
      onChange={(e) => setName(e.target.value)}
      placeholder="Enter your name"
    />
  );
}

value={name} binds the input to React state, and onChange updates that state on every keystroke — which means the input's current value always matches the state.

Multiple Fields — One Object State

Instead of creating a separate useState for every field, using a single object state plus one shared handler scales much better:

function ContactForm() {
  const [formData, setFormData] = useState({ name: '', email: '', message: '' });

  function handleChange(e) {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  }

  function handleSubmit(e) {
    e.preventDefault();
    console.log('Submitting:', formData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" value={formData.name} onChange={handleChange} placeholder="Name" />
      <input name="email" value={formData.email} onChange={handleChange} placeholder="Email" />
      <textarea name="message" value={formData.message} onChange={handleChange} placeholder="Message" />
      <button type="submit">Send</button>
    </form>
  );
}

The trick is that each input's name attribute matches an object key — so [name]: value (a computed property) lets one function handle every field.

Key Takeaways

  • Controlled component: the input's value comes from state, onChange updates that state.
  • For multiple fields, an object state plus one shared handleChange function scales well.
  • For complex forms (validation, error messages), libraries like React Hook Form are also available.
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Esc