DEV Community

Mahmood Hassan Rameem
Mahmood Hassan Rameem

Posted on

React Form Action

πŸ“˜ React Form Actions (With Examples)

πŸ”Ή Introduction

Forms are an essential part of any web application. They allow users to input data, which can be handled in React using state management and event handlers. Unlike plain HTML, React forms are usually controlled components, meaning the form input values are controlled by React state.


πŸ”Ή Basic Form Handling in React

Example: Simple Input Form

import React, { useState } from "react";

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

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevents page reload
    alert(`Hello, ${name}!`);
  };

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

export default SimpleForm;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Here, the input field is a controlled component because its value is bound to name state.


πŸ”Ή Multiple Inputs with One State

You can manage multiple form fields with a single state object.

Example:

import React, { useState } from "react";

function MultiForm() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
  });

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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="username"
        placeholder="Enter Username"
        value={formData.username}
        onChange={handleChange}
      />
      <br />
      <input
        type="email"
        name="email"
        placeholder="Enter Email"
        value={formData.email}
        onChange={handleChange}
      />
      <br />
      <input
        type="password"
        name="password"
        placeholder="Enter Password"
        value={formData.password}
        onChange={handleChange}
      />
      <br />
      <button type="submit">Register</button>
    </form>
  );
}

export default MultiForm;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This method makes it easy to scale forms with many fields.


πŸ”Ή Handling Checkbox, Radio, and Select

Different input types require slightly different handling.

Example:

import React, { useState } from "react";

function AdvancedForm() {
  const [gender, setGender] = useState("");
  const [agree, setAgree] = useState(false);
  const [country, setCountry] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log({ gender, agree, country });
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Radio Buttons */}
      <label>
        <input
          type="radio"
          name="gender"
          value="Male"
          onChange={(e) => setGender(e.target.value)}
        />
        Male
      </label>
      <label>
        <input
          type="radio"
          name="gender"
          value="Female"
          onChange={(e) => setGender(e.target.value)}
        />
        Female
      </label>

      <br />

      {/* Checkbox */}
      <label>
        <input
          type="checkbox"
          checked={agree}
          onChange={() => setAgree(!agree)}
        />
        I agree to the terms
      </label>

      <br />

      {/* Select Dropdown */}
      <select value={country} onChange={(e) => setCountry(e.target.value)}>
        <option value="">--Select Country--</option>
        <option value="Bangladesh">Bangladesh</option>
        <option value="India">India</option>
        <option value="USA">USA</option>
      </select>

      <br />

      <button type="submit">Submit</button>
    </form>
  );
}

export default AdvancedForm;
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Form Validation Example

You can add basic validation before submitting.

import React, { useState } from "react";

function ValidatedForm() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

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

    if (!email.includes("@")) {
      setError("Invalid email address");
      return;
    }

    setError("");
    alert("Form submitted successfully!");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        placeholder="Enter Email"
        onChange={(e) => setEmail(e.target.value)}
      />
      {error && <p style={{ color: "red" }}>{error}</p>}
      <button type="submit">Submit</button>
    </form>
  );
}

export default ValidatedForm;
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Key Points to Remember

  • Always use onChange to update state for controlled inputs.
  • Use e.preventDefault() to stop page reload on submit.
  • Store multiple input fields in a single object when possible.
  • Validation can be done before submission.
  • You can integrate with APIs by sending form data via fetch or axios.

⚑ This document covers React form actions with examples ranging from simple to advanced (validation, multiple fields, radio, checkbox, select).

Do you want me to also include an API integration example (submitting form data to a backend with fetch/axios)?

Top comments (0)