Skip to main content

Featured

🎉 Day 46 — React Mastery Completed (Final Summary & Congratulations!)

🎉 Day 46 — React Mastery Completed (Final Summary & Congratulations!) Congratulations, developer! 👏 You’ve successfully completed the 45-Day React.js Roadmap — from understanding the fundamentals to mastering advanced concepts like Redux, Routing, Testing, and Deployment. 📘 What You’ve Learned ✅ React basics — Components, JSX, Props, and State ✅ Hooks — useState, useEffect, useRef, useMemo, and Custom Hooks ✅ Context API and Redux Toolkit for global state management ✅ Routing with React Router & Protected Routes ✅ Data fetching using Fetch API, Axios, React Query ✅ Advanced Patterns — Compound Components, Render Props, HOCs ✅ Styling — CSS Modules, Styled Components, Theming ✅ Animations, Accessibility, Testing, and Performance Optimization ✅ Deployment on Vercel, Netlify, or GitHub Pages 🧩 Final Project Ideas Now that you’re done, build real-world apps to polish your skills: 📝 Task ...

📘 Day 10 — Handling Forms: Controlled vs Uncontrolled Components

📘 Day 10 — Handling Forms: Controlled vs Uncontrolled Components

Forms are an essential part of web applications. In React, form handling can be done using two main approaches: Controlled Components and Uncontrolled Components.

🔹 Controlled Components

In controlled components, form data is handled by React’s state. The value of each input is controlled through state updates.

import React, { useState } from "react";

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

  const handleSubmit = (e) => {
    e.preventDefault();
    alert("Hello, " + name);
  };

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

export default ControlledForm;
  

🔸 Uncontrolled Components

Uncontrolled components let the DOM handle the form data instead of React. You can use a ref to access the form value.

import React, { useRef } from "react";

function UncontrolledForm() {
  const nameRef = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();
    alert("Hello, " + nameRef.current.value);
  };

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

export default UncontrolledForm;
  

Use controlled components for better React integration and predictable state management. Use uncontrolled ones for simpler, non-reactive forms.

Comments