4.9 🧠 Forms in React – Building Dynamic Forms

Table of Contents


📦 Why Forms Matter in Web Apps

Forms are like the way users talk to your website.

They let people:

  • Sign up or log in
  • Search for things
  • Fill contact details
  • Give feedback, and more!

React gives you powerful tools to handle these forms smoothly 💪


🧍 Controlled vs Uncontrolled Forms

Let’s start with the difference between Controlled and Uncontrolled components.

TypeControlled FormUncontrolled Form
Data HandlingReact controls the form dataThe DOM (browser) controls the form
Easy to Validate?✅ Yes❌ Tricky
Use CaseMost common in React appsRare cases, like quick demo

✅ Controlled Component Example

jsxCopyEditimport { useState } from "react";

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

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevent page reload
    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">Say Hi</button>
    </form>
  );
}

❌ Uncontrolled Component Example

jsxCopyEditimport { useRef } from "react";

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

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Hello, ${inputRef.current.value}!`);
  };

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

🧠 Use controlled forms for better control and validation.


✍️ Handling Form Submissions

When a user clicks “Submit”, we often want to:

  1. Stop the page from reloading
  2. Validate input
  3. Send data somewhere (like an API)

Steps:

jsxCopyEditconst handleSubmit = (e) => {
  e.preventDefault(); // Stops the page reload
  // Add your logic here
};

You can even use console.log to check what the user typed.


🔎 Adding Validation

Let’s say we want to make sure the user enters a name:

jsxCopyEditconst handleSubmit = (e) => {
  e.preventDefault();
  if (!name.trim()) {
    alert("Please enter a name");
    return;
  }
  alert(`Welcome, ${name}`);
};

You can also:

  • Check for emails
  • Set minimum password lengths
  • Show inline error messages

📋 Building Bigger Forms

Imagine a form with name, email, and password fields. Here’s a basic structure:

jsxCopyEditconst [form, setForm] = useState({ name: "", email: "", password: "" });

<input
  name="email"
  value={form.email}
  onChange={(e) => setForm({ ...form, [e.target.name]: e.target.value })}
/>

✅ This method keeps all fields in one object. It’s clean and scalable.


🔧 Third-Party Helpers: Formik & React Hook Form

🚀 Formik

Formik simplifies form logic.

bashCopyEditnpm install formik

Example:

jsxCopyEditimport { useFormik } from "formik";

const formik = useFormik({
  initialValues: { email: "" },
  onSubmit: (values) => alert(JSON.stringify(values)),
});

🔧 React Hook Form

It’s fast, small, and easy to use.

bashCopyEditnpm install react-hook-form

Example:

jsxCopyEditimport { useForm } from "react-hook-form";

const { register, handleSubmit } = useForm();

<form onSubmit={handleSubmit((data) => console.log(data))}>
  <input {...register("email")} />
  <button type="submit">Submit</button>
</form>

👉 These tools help you save time and write cleaner code.


🧠 Controlled vs Uncontrolled – Summary Table

FeatureControlledUncontrolled
Recommended?✅ Yes❌ No
Data SourceuseStateuseRef
Best forReal appsQuick demos
Easy to validate✅ Yes❌ No

📊 Infographic – Form Flow in React

Form Flow In React – Controlled Vs Uncontrolled&Quot; Infographic
4.9 🧠 Forms In React – Building Dynamic Forms 2


🏁 Conclusion

Forms are super important in React apps.
They help users connect with your site 💬

Remember:

  • Use controlled components
  • Validate before submit ✅
  • Use Formik or React Hook Form for big forms

📣 Want more awesome React content?

👉 Subscribe to Web Codder for hands-on tutorials and fun coding projects!
📺 YouTube: Web Codder
📸 Instagram: @web_codder_official
💬 Join us on WhatsApp for updates, tips, and challenges!

Share the Post:
Picture of Web Codder

Web Codder

Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.

Related Posts