ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

React.js Tutorial• 6 min read

Forms, Controlled Components & Inputs

Single source of truth with value/onChange, textareas, and select dropdowns

In React, form inputs are "controlled" by binding the input's value attribute to React state and updating it via onChange handlers, keeping state as the single source of truth.

Controlled vs Uncontrolled Inputs

Controlled Component: React state governs the value displayed inside the form field: <input value={name} onChange={(e) => setName(e.target.value)} />.

Form Submission: Call e.preventDefault() inside onSubmit to prevent default full-page browser POST reloads.

Multi-Field Forms: Manage form objects with a single state handler using computed property names: setForm({ ...form, [e.target.name]: e.target.value }).

Multi-Field Controlled Form
function SignupForm() {
  const [formData, setFormData] = React.useState({ username: "", email: "", role: "student" });

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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Submitted user payload:", formData);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <input name="username" value={formData.username} onChange={handleChange} placeholder="Username" required />
      <input name="email" type="email" value={formData.email} onChange={handleChange} placeholder="Email" required />
      <button type="submit">Register</button>
    </form>
  );
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What method must be called on the submit event in React to prevent the browser from performing a full page reload?