OnlineCBT Logo OnlineCBT
React Tutorial
REACT · LESSON 9

Forms and Controlled Components

By Ratan Updated: 16 Oct 2026

Build interactive form inputs bound to component state (Controlled Components).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. Controlled vs Uncontrolled Components

  • Uncontrolled: Form inputs manage their own state internally in the DOM. You pull values using a ref.
  • Controlled (Recommended): React state is the single source of truth. Every keystroke updates React state, and the input value is bound directly to that state variable.

2. Single Input Controlled Component

import { useState } from 'react';

function SearchBar({ onSearch }) {
  const [query, setQuery] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    onSearch(query);
  };

  return (
    
setQuery(e.target.value)} />
); }

3. Managing Multi-Field Forms Elegantly

Instead of creating a separate useState for every input, manage all fields inside a single state object using dynamic object keys [e.target.name]:

function StudentRegistration() {
  const [formData, setFormData] = useState({
    fullName: "",
    email: "",
    examCategory: "NEET",
    agreedToTerms: false
  });

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

  const handleRegister = (e) => {
    e.preventDefault();
    console.log("Submitting payload:", formData);
  };

  return (
    
); }

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat