DEV Community

Cover image for Understanding Forms in React
Arul .A
Arul .A

Posted on

Understanding Forms in React

Understanding Forms in React

Forms are one of the most common ways users interact with web applications. Whether it's a login page, registration form, search bar, or contact form, React provides a simple and efficient way to handle form data.

What is a Form in React?

A form is used to collect user input. In React, form elements such as <input>, <textarea>, and <select> are typically controlled using state.

Example:

function LoginForm() {
  const [username, setUsername] = useState("");

  return (
    <input
      type="text"
      value={username}
      onChange={(e) => setUsername(e.target.value)}
      placeholder="Enter username"
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • value connects the input to React state.
  • onChange updates the state whenever the user types.
  • React becomes the single source of truth for the input value.

Controlled Components

A controlled component is an input element whose value is controlled by React state.

import { useState } from "react";

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

  return (
    <input
      value={name}
      onChange={(e) => setName(e.target.value)}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. User types in the input.
  2. onChange event fires.
  3. State updates using setName.
  4. Component re-renders.
  5. Input displays the latest state value.

Flow:

User Input
    ↓
onChange Event
    ↓
State Update
    ↓
Re-render
    ↓
Updated UI
Enter fullscreen mode Exit fullscreen mode

Handling Multiple Inputs

Instead of creating separate states for every field, use a single object.

import { useState } from "react";

function RegisterForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: ""
  });

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

  return (
    <>
      <input
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Name"
      />

      <input
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email"
      />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Why Use [e.target.name]?

[e.target.name]: e.target.value
Enter fullscreen mode Exit fullscreen mode

This dynamically updates the field that triggered the event.

If:

e.target.name = "email"
Enter fullscreen mode Exit fullscreen mode

then:

{
  email: "arul@example.com"
}
Enter fullscreen mode Exit fullscreen mode

gets updated automatically.


Form Submission

Use the onSubmit event on the form.

function LoginForm() {
  const [email, setEmail] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    console.log(email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={email}
        onChange={(e) =>
          setEmail(e.target.value)
        }
      />

      <button type="submit">
        Submit
      </button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Why preventDefault()?

By default, submitting a form refreshes the page.

e.preventDefault();
Enter fullscreen mode Exit fullscreen mode

prevents the page reload and allows React to handle the submission.


Handling Checkboxes

const [isChecked, setIsChecked] =
  useState(false);

<input
  type="checkbox"
  checked={isChecked}
  onChange={(e) =>
    setIsChecked(e.target.checked)
  }
/>
Enter fullscreen mode Exit fullscreen mode

For checkboxes, use:

e.target.checked
Enter fullscreen mode Exit fullscreen mode

instead of:

e.target.value
Enter fullscreen mode Exit fullscreen mode

Handling Select Dropdowns

const [country, setCountry] =
  useState("");

<select
  value={country}
  onChange={(e) =>
    setCountry(e.target.value)
  }
>
  <option value="">Select</option>
  <option value="India">India</option>
  <option value="USA">USA</option>
</select>
Enter fullscreen mode Exit fullscreen mode

Basic Form Validation

const handleSubmit = (e) => {
  e.preventDefault();

  if (!email) {
    alert("Email is required");
    return;
  }

  console.log("Form Submitted");
};
Enter fullscreen mode Exit fullscreen mode

Common validations:

  • Required fields
  • Email format
  • Password length
  • Confirm password matching

Controlled vs Uncontrolled Components

Controlled Component

<input
  value={name}
  onChange={(e) =>
    setName(e.target.value)
  }
/>
Enter fullscreen mode Exit fullscreen mode
  • Managed by React state
  • Easier validation
  • Preferred approach

Uncontrolled Component

const inputRef = useRef();

<input ref={inputRef} />
Enter fullscreen mode Exit fullscreen mode
  • Managed by the DOM
  • Uses refs to access values
  • Less common in React applications

Best Practices

  • Use controlled components

  • Store related fields in a single state object

  • Validate before submission

  • Use meaningful field names

  • Prevent default form submission

  • Reuse a common handleChange function


Conclusion

React forms are built around state management. By using controlled components, handling events with onChange, and managing submissions with onSubmit, you can build scalable and maintainable forms.

Key concepts to remember:

  • Controlled Components
  • useState
  • onChange
  • onSubmit
  • preventDefault()
  • Form Validation
  • Handling Multiple Inputs

Mastering forms is a crucial step toward building real-world React applications.

Top comments (0)