0
0
ReactDebug / FixBeginner · 3 min read

How to Handle Form Submit in React: Simple Guide

In React, handle form submission by adding an onSubmit event handler to the <form> element and calling event.preventDefault() inside the handler to stop the page from reloading. Then, process the form data as needed within that handler function.
🔍

Why This Happens

When you submit a form in React without preventing the default behavior, the browser reloads the page. This happens because HTML forms naturally try to send data and refresh the page on submit.

jsx
import React from 'react';

function MyForm() {
  function handleSubmit(event) {
    alert('Form submitted');
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Output
Page reloads immediately after clicking Submit, so alert may not show or disappears quickly.
🔧

The Fix

To fix this, call event.preventDefault() inside the submit handler. This stops the page reload and lets you handle the form data smoothly.

jsx
import React from 'react';

function MyForm() {
  function handleSubmit(event) {
    event.preventDefault();
    alert('Form submitted without page reload');
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
Output
Alert box shows 'Form submitted without page reload' and page does not reload.
🛡️

Prevention

Always use event.preventDefault() in form submit handlers to avoid unwanted page reloads. Use controlled components to manage form inputs and keep state updated. Use descriptive function names like handleSubmit and keep your form logic inside this handler for clarity.

Enable linting rules like react-hooks/rules-of-hooks and jsx-a11y/no-noninteractive-element-interactions to catch common mistakes early.

⚠️

Related Errors

Common related errors include:

  • Not binding this in class components for handlers (legacy pattern).
  • Using onClick on the submit button without onSubmit on the form, which can miss keyboard submits.
  • Forgetting to set type="submit" on the button, so the form does not submit.

Key Takeaways

Use onSubmit on the <form> element to handle form submission in React.
Call event.preventDefault() inside the submit handler to stop page reload.
Keep form inputs controlled with React state for better data handling.
Name your submit handler clearly, like handleSubmit, for readability.
Avoid using onClick on buttons alone for form submission to support accessibility.