Popular Searches
Popular Course Categories
Popular Courses

Form Submission

Form Submission

React Forms

Form Submission in React JS – Complete Detailed Notes

Topic: Form Submission in React JS

Course: React JS Training

1. Introduction to Form Submission

Form submission in React JS is the process of collecting information entered by a user, validating the data, and processing it when the user submits a form. Forms are commonly used for login pages, registration pages, contact forms, feedback forms, search boxes, checkout pages, and other interactive features.

React allows developers to handle form submissions using event handlers such as onSubmit, state management with useState, and JavaScript functions. Form data can be validated, displayed, stored, or sent to a backend API.

2. What Is Form Submission?

Form submission occurs when a user sends the information entered into a form by clicking a submit button or pressing Enter in an appropriate input field.

For example, when a user enters an email address and password on a login page and clicks the Login button, the form submission handler processes the entered information.

Common Uses of Form Submission

  • User registration and account creation.
  • Login and authentication forms.
  • Contact and enquiry forms.
  • Search forms and filters.
  • Feedback and survey forms.
  • Online shopping checkout forms.
  • Job application and course registration forms.

3. How Form Submission Works in React

A typical React form submission follows these steps:

  1. The user enters information into the form fields.
  2. React updates the input state when controlled fields are used.
  3. The user clicks the Submit button or presses Enter.
  4. The form triggers the onSubmit event handler.
  5. The handler calls event.preventDefault() when the default browser submission should be prevented.
  6. The application validates the entered information.
  7. If the data is valid, the application processes it or sends it to a backend API.
  8. The application displays a success message or an appropriate error message.

4. Understanding the onSubmit Event

The onSubmit event is a React event handler attached to a form element. It runs when the form is submitted.

In React JSX, event names use camelCase. Therefore, developers use onSubmit instead of the lowercase HTML-style onsubmit.

Basic Syntax

function handleSubmit(event) {
  event.preventDefault();
  // Process the submitted form
}
function MyForm() {
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="username" />
      <button type="submit">Submit</button>
    </form>
  );
}

Here, handleSubmit is called when the user submits the form. Passing handleSubmit as a function reference allows React to execute it when the event occurs.

5. Understanding event.preventDefault()

By default, a browser form submission can navigate to a URL or reload the page. In a typical client-side React form, developers often want to handle the submitted information without a full-page reload.

The event.preventDefault() method prevents the browser's default submission behavior, allowing React code to handle the submission.

Example

function handleSubmit(event) {
  event.preventDefault();
  console.log("Form submitted successfully!");
}

Why Is preventDefault() Important?

  • Prevents an unwanted full-page refresh for client-side form handling.
  • Allows the application to process data using JavaScript.
  • Makes it possible to display success or error messages without navigating away.
  • Allows developers to submit data through an API request.

Important: preventDefault() is not always necessary. If you intentionally use a normal HTML form submission or React's supported form action pattern, the submission flow may be different.

6. Creating a Simple Form in React

Let's create a basic form that accepts a user's name and displays a message after submission.

Example Code

import { useState } from "react";
function SimpleForm() {
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");
  function handleSubmit(event) {
    event.preventDefault();
    if (!name.trim()) {
      setMessage("Please enter your name.");
      return;
    }
    setMessage(`Welcome, ${name}! Form submitted successfully.`);
  }
  return (
    <div>
      <h2>Simple React Form</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Name:</label>
        <input
          id="name"
          type="text"
          value={name}
          onChange={(event) => setName(event.target.value)}
          placeholder="Enter your name"
        />
        <button type="submit">Submit</button>
      </form>
      {message && <p>{message}</p>}
    </div>
  );
}
export default SimpleForm;

Explanation

  • useState("") creates state variables for the name and message.
  • value={name} connects the input field to React state.
  • onChange updates the name whenever the user types.
  • onSubmit={handleSubmit} connects the form to its submission handler.
  • event.preventDefault() prevents the browser's default form submission.
  • name.trim() checks whether the name contains meaningful text.
  • The message is displayed after successful validation or when the name is missing.

7. Controlled Components and Form Submission

A controlled component is an input element whose current value is controlled by React state. Controlled inputs make it easier to validate data, update the interface, and prepare form information for submission.

Example

import { useState } from "react";
function EmailForm() {
  const [email, setEmail] = useState("");
  function handleSubmit(event) {
    event.preventDefault();
    console.log("Submitted email:", email);
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email:</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />
      <button type="submit">Submit Email</button>
    </form>
  );
}
export default EmailForm;

In this example, React maintains the email value in state. When the form is submitted, the handler reads the latest state value.

8. Handling Multiple Form Fields

Real-world forms usually contain multiple fields, such as name, email, phone number, and message. These values can be stored in one state object.

Example

import { useState } from "react";
function ContactForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    message: ""
  });
  const [status, setStatus] = useState("");
  function handleChange(event) {
    const { name, value } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  }
  function handleSubmit(event) {
    event.preventDefault();
    if (!formData.name.trim() || !formData.email.trim() ||
        !formData.message.trim()) {
      setStatus("Please complete all fields.");
      return;
    }
    console.log("Submitted data:", formData);
    setStatus("Your message has been submitted.");
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="contact-name">Name:</label>
      <input
        id="contact-name"
        name="name"
        value={formData.name}
        onChange={handleChange}
        required
      />
      <label htmlFor="contact-email">Email:</label>
      <input
        id="contact-email"
        name="email"
        type="email"
        value={formData.email}
        onChange={handleChange}
        required
      />
      <label htmlFor="contact-message">Message:</label>
      <textarea
        id="contact-message"
        name="message"
        value={formData.message}
        onChange={handleChange}
        required
      />
      <button type="submit">Send Message</button>
      {status && <p>{status}</p>}
    </form>
  );
}
export default ContactForm;

Key Concepts

  • formData stores the values of all fields.
  • name identifies which property should be updated.
  • The spread operator (...) preserves the other properties.
  • The computed property [name] updates the matching field.
  • The submit handler validates the data before processing it.

9. Submitting Uncontrolled Forms with FormData

React also supports uncontrolled inputs, where the browser manages the current input values. You can use the browser's FormData API to read fields when the form is submitted. Every field you want to retrieve should have a name attribute.

Example

function SearchForm() {
  function handleSubmit(event) {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const query = formData.get("query");
    console.log("Search query:", query);
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="query">Search:</label>
      <input id="query" name="query" type="text" required />
      <button type="submit">Search</button>
    </form>
  );
}
export default SearchForm;

new FormData(event.currentTarget) collects the form fields. formData.get("query") retrieves the value associated with the field named query.

10. Form Submission with Validation

Validation checks whether the information entered by a user meets the application's requirements. It helps prevent incomplete or incorrectly formatted data from being processed.

Common Validation Rules

  • Name must not be empty.
  • Email must use a valid email format.
  • Password must meet the application's password requirements.
  • Phone number must follow the expected format.
  • Required fields must be completed.
  • Checkboxes such as terms and conditions may need to be selected.

Example: Email Validation

import { useState } from "react";
function EmailValidationForm() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  function handleSubmit(event) {
    event.preventDefault();
    setError("");
    setSuccess("");
    if (!email.trim()) {
      setError("Email is required.");
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError("Please enter a valid email address.");
      return;
    }
    setSuccess("Email submitted successfully.");
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="validation-email">Email:</label>
      <input
        id="validation-email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />
      <button type="submit">Submit</button>
      {error && <p role="alert">{error}</p>}
      {success && <p role="status">{success}</p>}
    </form>
  );
}
export default EmailValidationForm;

Note: Client-side validation improves the user experience but is not a security boundary. A backend must validate submitted data independently.

11. Form Submission with Checkboxes and Select Fields

Forms may contain checkboxes, radio buttons, dropdowns, and other controls. A checkbox is commonly controlled using the checked property, while a text input or select field commonly uses value.

Example

import { useState } from "react";
function PreferencesForm() {
  const [course, setCourse] = useState("React JS");
  const [accepted, setAccepted] = useState(false);
  const [status, setStatus] = useState("");
  function handleSubmit(event) {
    event.preventDefault();
    if (!accepted) {
      setStatus("Please accept the terms and conditions.");
      return;
    }
    setStatus(`Selected course: ${course}. Form submitted.`);
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="course">Choose a course:</label>
      <select
        id="course"
        value={course}
        onChange={(event) => setCourse(event.target.value)}
      >
        <option value="React JS">React JS</option>
        <option value="Flutter">Flutter</option>
        <option value="Selenium">Selenium</option>
      </select>
      <label>
        <input
          type="checkbox"
          checked={accepted}
          onChange={(event) => setAccepted(event.target.checked)}
        />
        I accept the terms and conditions.
      </label>
      <button type="submit">Register</button>
      {status && <p>{status}</p>}
    </form>
  );
}
export default PreferencesForm;

12. Sending Form Data to an API

In real applications, form submission often sends data to a backend server using an HTTP request. The backend may save the information in a database, create an account, send an email, or perform another operation.

Example Using fetch()

import { useState } from "react";
function RegistrationForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  async function handleSubmit(event) {
    event.preventDefault();
    setStatus("");
    setIsSubmitting(true);
    try {
      const response = await fetch("/api/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ name, email })
      });
      if (!response.ok) {
        throw new Error("Registration request failed.");
      }
      setStatus("Registration successful.");
      setName("");
      setEmail("");
    } catch (error) {
      setStatus(error.message || "Something went wrong.");
    } finally {
      setIsSubmitting(false);
    }
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="register-name">Name:</label>
      <input
        id="register-name"
        value={name}
        onChange={(event) => setName(event.target.value)}
        required
      />
      <label htmlFor="register-email">Email:</label>
      <input
        id="register-email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? "Submitting..." : "Register"}
      </button>
      {status && <p role="status">{status}</p>}
    </form>
  );
}
export default RegistrationForm;

Important: /api/register is an example endpoint. Replace it with a real endpoint provided by your backend. The server must validate the submitted data and apply appropriate authentication, authorization, and security controls.

What Happens in This Example?

  1. The user enters their name and email.
  2. The submit handler prevents the default browser submission.
  3. The submitting state is enabled to show progress and disable repeat submissions.
  4. fetch() sends a POST request containing JSON data.
  5. The response status is checked to identify unsuccessful requests.
  6. The interface displays success or error feedback.
  7. The submitting state is reset in the finally block.

13. Submit Button and Button Types

HTML buttons inside forms can have different types. Specifying the correct type helps avoid unexpected submissions.

Button Type Purpose Example
submit Submits the form. <button type="submit">Save</button>
button Runs a custom action without submitting the form automatically. <button type="button">Preview</button>
reset Resets fields to their initial values. <button type="reset">Reset</button>

Use type="submit" for the intended submit button and type="button" for other buttons inside a form. A button inside a form defaults to submit behavior when its type is omitted.

14. Resetting a Form After Submission

After successful submission, an application may clear the input fields. With controlled components, reset the corresponding React state values.

Example

import { useState } from "react";
function FeedbackForm() {
  const [feedback, setFeedback] = useState("");
  const [message, setMessage] = useState("");
  function handleSubmit(event) {
    event.preventDefault();
    if (!feedback.trim()) {
      setMessage("Please enter your feedback.");
      return;
    }
    console.log("Feedback:", feedback);
    setMessage("Thank you for your feedback!");
    setFeedback("");
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="feedback">Feedback:</label>
      <textarea
        id="feedback"
        value={feedback}
        onChange={(event) => setFeedback(event.target.value)}
        required
      />
      <button type="submit">Submit Feedback</button>
      {message && <p>{message}</p>}
    </form>
  );
}
export default FeedbackForm;

15. Handling Loading and Submission Errors

When a form submits data to a server, the request may take time or fail. A well-designed form provides feedback while the request is running and when a problem occurs.

  • Use a loading state to indicate that the request is in progress.
  • Disable the submit button when necessary to reduce accidental duplicate submissions.
  • Display useful error messages when a request fails.
  • Do not show a success message until the operation has actually succeeded.
  • Restore the loading state in a finally block.
  • Consider retry behavior and duplicate-request handling for important operations.

16. Common Mistakes in React Form Submission

Mistake Why It Is a Problem Correct Approach
Forgetting preventDefault() The browser may reload or navigate away during conventional client-side submission. Call event.preventDefault() when handling submission manually.
Using onClick instead of form onSubmit Enter-key submission and form-level validation may not be handled consistently. Attach the handler to the form's onSubmit.
Calling the handler immediately onSubmit={handleSubmit()} executes the function during rendering. Use onSubmit={handleSubmit}.
Missing input names when using FormData Fields cannot be retrieved by the expected key. Add appropriate name attributes.
Not validating input Incomplete or malformed information may be processed. Use suitable browser and custom validation.
Ignoring API errors The interface may report success when the request failed. Check response.ok and handle failures.
Not resetting loading state The submit button may remain disabled after an error. Use finally for cleanup.
Using an incorrect button type Buttons intended for other actions may submit the form. Set button types explicitly.
Relying only on client-side validation Client-side checks can be bypassed. Validate all important data on the server too.

17. Best Practices for Form Submission

  • Use semantic HTML elements such as <form>, <label>, and <button>.
  • Connect labels to inputs using matching htmlFor and id values.
  • Use onSubmit for form-level submission logic.
  • Use controlled inputs when the interface needs to track and validate field values.
  • Use FormData when reading uncontrolled fields at submission time is suitable.
  • Provide clear validation, success, and error messages.
  • Display a loading state during asynchronous requests.
  • Never trust client-side validation alone.
  • Protect sensitive information and avoid logging passwords or other secrets.
  • Keep submission logic readable and separate reusable logic into functions or custom hooks when appropriate.
  • Test submission by clicking the button and by pressing Enter in a relevant field.

18. Form Submission: Controlled Components vs FormData

Feature Controlled Components FormData Approach
Value management React state manages input values. The browser manages uncontrolled input values.
Reading values Read from state. Read using new FormData(form).
Live validation Convenient for validation as the user types. Often suitable for reading and validating on submission.
Resetting Update state values. Can use native form reset behavior or DOM defaults, depending on the implementation.
Best suited for Dynamic forms, conditional fields, and interactive validation. Simpler forms where values are primarily needed at submission time.

19. Mini Project: Student Registration Form

This mini project combines form submission, controlled inputs, validation, and a confirmation message.

import { useState } from "react";
function StudentRegistration() {
  const [formData, setFormData] = useState({
    fullName: "",
    email: "",
    course: "React JS"
  });
  const [message, setMessage] = useState("");
  function handleChange(event) {
    const { name, value } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  }
  function handleSubmit(event) {
    event.preventDefault();
    if (!formData.fullName.trim() || !formData.email.trim()) {
      setMessage("Please complete all required fields.");
      return;
    }
    setMessage(
      `Thank you, ${formData.fullName}! Your ${formData.course} registration has been received.`
    );
    console.log("Registration details:", formData);
  }
  return (
    <div>
      <h2>Student Registration</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="fullName">Full Name:</label>
        <input
          id="fullName"
          name="fullName"
          value={formData.fullName}
          onChange={handleChange}
          required
        />
        <label htmlFor="studentEmail">Email Address:</label>
        <input
          id="studentEmail"
          name="email"
          type="email"
          value={formData.email}
          onChange={handleChange}
          required
        />
        <label htmlFor="studentCourse">Select Course:</label>
        <select
          id="studentCourse"
          name="course"
          value={formData.course}
          onChange={handleChange}
        >
          <option value="React JS">React JS</option>
          <option value="Flutter">Flutter</option>
          <option value="Selenium">Selenium</option>
        </select>
        <button type="submit">Register</button>
      </form>
      {message && <p role="status">{message}</p>}
    </div>
  );
}
export default StudentRegistration;

Project Features

  • Accepts a student's full name and email address.
  • Allows the student to select a course.
  • Stores the input values in React state.
  • Uses one handler to update multiple fields.
  • Handles form submission without a full-page refresh.
  • Displays a confirmation message after validation.

Project limitation: This example displays a confirmation message and logs the data in the browser console. It does not save registrations to a database. A backend API is needed for persistent storage.

20. Interview Questions and Answers

Q1. What is form submission in React JS?

Form submission is the process of collecting and processing user-entered data using a form event handler such as onSubmit.

Q2. What is the purpose of onSubmit?

The onSubmit event handler runs when a form is submitted, allowing the application to validate and process the entered data.

Q3. Why do we use event.preventDefault()?

It prevents the browser's default submission behavior when the application needs to handle the submission itself, such as sending data through an API without a full-page reload.

Q4. What is a controlled component?

A controlled component is an input whose current value is managed by React state through properties such as value and checked.

Q5. What is FormData?

FormData is a browser API that collects form field values. It can be used to read fields by their name attributes or to send form data in a request.

Q6. How do you submit form data to an API?

Use a request method such as fetch() inside the submission handler, send the required payload, check the response, and handle loading and error states.

Q7. What is the difference between onSubmit and onClick?

onSubmit handles the form submission event, including submission initiated through Enter where applicable. onClick handles a click on a particular element and is not a replacement for form-level submission handling.

Q8. How can you prevent submission when fields are empty?

Validate the input values in the submission handler and return early if required fields are missing. HTML attributes such as required can also provide native browser validation.

Q9. How can you reset controlled form inputs?

Set the React state values back to their initial values after successful submission or when the user requests a reset.

Q10. Is client-side validation sufficient for security?

No. Client-side validation improves usability, but the server must validate incoming data independently because browser-side checks can be bypassed.

21. Practical Exercises

  1. Create a login form with username and password fields.
  2. Create a registration form with name, email, and phone number fields.
  3. Display the submitted information below the form after successful validation.
  4. Prevent submission when required fields are empty.
  5. Create a feedback form that clears the textarea after submission.
  6. Create a course selection form using a dropdown and checkbox.
  7. Send form data to a test API and display the response status.
  8. Add a loading indicator and disable the submit button while an API request is running.
  9. Display separate success and error messages.
  10. Test form submission using both the mouse and keyboard.

22. Quick Revision

  • <form> groups related input fields.
  • onSubmit handles the form submission event.
  • event.preventDefault() prevents the default browser behavior when manual client-side handling is required.
  • useState stores controlled input values and submission status.
  • FormData collects values from form fields that have appropriate names.
  • Validation checks whether entered data meets the required rules.
  • fetch() can send submitted data to a backend API.
  • Loading, success, and error states improve the user experience.
  • Backend validation is essential for security and data integrity.

23. Conclusion

Form submission is an essential part of building interactive React JS applications. By understanding the onSubmit event, event.preventDefault(), controlled inputs, FormData, validation, and API requests, developers can create forms that collect information reliably and provide useful feedback to users.

Practice with login forms, registration forms, search forms, and contact forms to strengthen your understanding of form submission in React JS.

24. React JS Training and Course Demo

Learn more about React JS concepts, practical development, and interactive forms through the following resources:

25. Official React Documentation

Previous Next
whatsapp