Courses/React/Forms and Controlled Components

    Lesson 6 • Intermediate

    Forms and Controlled Components ⚛️

    Build forms that React controls — from text inputs and dropdowns to validation and submission patterns.

    What You'll Learn in This Lesson

    • • Controlled vs uncontrolled components
    • • Handling text, select, checkbox, and radio inputs
    • • Client-side form validation with error messages
    • • Form submission with loading states
    • • When to use form libraries (React Hook Form, Formik)

    1️⃣ Controlled Components

    In a controlled component, React state is the "single source of truth." The input's value is always driven by state, and every change flows through onChangesetState → re-render.

    Try It: Controlled Inputs

    See how React manages input state step by step

    Try it Yourself »
    JavaScript
    // Controlled Components — React Controls the Input
    console.log("=== Controlled vs Uncontrolled ===");
    console.log();
    console.log("CONTROLLED: React state drives the input value");
    console.log("  <input value={name} onChange={e => setName(e.target.value)} />");
    console.log("  React is the 'single source of truth'");
    console.log();
    console.log("UNCONTROLLED: DOM manages its own state");
    console.log("  <input ref={inputRef} />");
    console.log("  Read value with inputRef.current.value");
    console.log
    ...

    2️⃣ Different Input Types

    React handles different input types slightly differently. Text inputs use value, checkboxes use checked, and selects use value on the select element (not on options like in HTML).

    Try It: Input Types

    Handle text, select, checkbox, and radio inputs

    Try it Yourself »
    JavaScript
    // Different Input Types in React
    console.log("=== Text, Number, Email ===");
    console.log("<input type='text' value={name} onChange={handleChange} />");
    console.log("<input type='number' value={age} onChange={handleChange} />");
    console.log("<input type='email' value={email} onChange={handleChange} />");
    console.log("<input type='password' value={pass} onChange={handleChange} />");
    console.log();
    
    console.log("=== Textarea ===");
    console.log("// In HTML: <textarea>content</textarea>");
    console.l
    ...

    3️⃣ Form Validation

    Good validation provides immediate feedback. Validate on blur (when user leaves a field) for real-time UX, and validate on submit as a final check. Show errors only for fields the user has interacted with.

    Try It: Validation

    Build a validation function with clear error messages

    Try it Yourself »
    JavaScript
    // Form Validation
    console.log("=== Client-Side Validation ===");
    console.log();
    
    function validateForm(data) {
      const errors = {};
      
      if (!data.name.trim()) {
        errors.name = "Name is required";
      } else if (data.name.length < 2) {
        errors.name = "Name must be at least 2 characters";
      }
      
      if (!data.email.trim()) {
        errors.email = "Email is required";
      } else if (!/\S+@\S+\.\S+/.test(data.email)) {
        errors.email = "Invalid email format";
      }
      
      if (!data.password) {
        erro
    ...

    4️⃣ Form Submission

    A complete form component handles validation, loading states, error feedback, and success messages. Always call e.preventDefault() and disable the submit button while processing.

    Try It: Form Submission

    Complete form with validation and async submission

    Try it Yourself »
    JavaScript
    // Form Submission — Complete Pattern
    console.log("=== Full Form Component ===");
    console.log();
    console.log("function ContactForm() {");
    console.log("  const [form, setForm] = useState({");
    console.log("    name: '', email: '', message: ''");
    console.log("  });");
    console.log("  const [errors, setErrors] = useState({});");
    console.log("  const [isSubmitting, setIsSubmitting] = useState(false);");
    console.log("  const [submitted, setSubmitted] = useState(false);");
    console.log();
    console.log("  
    ...

    ⚠️ Common Mistakes

    ⚠️
    Missing value prop — An input with onChange but no value becomes uncontrolled. React will warn you.
    ⚠️
    Using onChange with checkbox value — Checkboxes use e.target.checked, not e.target.value.
    💡
    Pro Tip: For complex forms with many fields, use React Hook Form — it reduces boilerplate and improves performance by minimizing re-renders.

    📋 Quick Reference

    Input TypeReact Pattern
    Text/Emailvalue={val} onChange={e => set(e.target.value)}
    Checkboxchecked={val} onChange={e => set(e.target.checked)}
    Select<select value={val} onChange={fn}>
    Submit<form onSubmit={handleSubmit}>
    Prevent reloade.preventDefault()

    🎉 Lesson Complete!

    You can now build and validate any form in React! Next, we'll add navigation and routing to create multi-page apps.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service