Handling Forms and Controlled Inputs in React

React handles form inputs differently than plain HTML.
It uses something called controlled components, meaning: The input value is controlled by React state.

✅ Basic Controlled Input Example

import { useState } from "react";

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

  const handleChange = (e) => {
    setName(e.target.value); // update state as user types
  };

  const handleSubmit = (e) => {
    e.preventDefault(); // prevent page reload
    alert(`Hello, ${name}!`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name}
        onChange={handleChange}
        placeholder="Enter your name"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

✅ Multiple Inputs (Using One State Object)

function LoginForm() {
  const [formData, setFormData] = useState({ username: "", password: "" });

  const handleChange = (e) => {
    const { name, value } = e.target;

    setFormData({
      ...formData,
      [name]: value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Login Info:", formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="username"
        value={formData.username}
        onChange={handleChange}
        placeholder="Username"
      />
      <input
        name="password"
        type="password"
        value={formData.password}
        onChange={handleChange}
        placeholder="Password"
      />
      <button type="submit">Login</button>
    </form>
  );
}

🧠 Using one state object (formData) makes it easy to manage multiple fields.

✅ Summary: Controlled Inputs

ConceptDescription
Controlled ComponentInput’s value is tied to React state
onChangeUpdates state as user types
value={...}Makes sure the input reflects state
preventDefault()Stops form from reloading the page

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *