0
0
ReactDebug / FixBeginner · 3 min read

How to Handle onSubmit Event in React: Simple Fix and Best Practices

In React, handle the onSubmit event by passing a function to the form's onSubmit attribute and calling event.preventDefault() inside that function to stop the page from reloading. This lets you control what happens when the form is submitted, like reading input values or sending data.
🔍

Why This Happens

When you add an onSubmit handler in React but forget to prevent the default browser behavior, the page reloads on form submission. This happens because HTML forms naturally try to send data and reload the page, which interrupts React's control flow.

jsx
import React from 'react';

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

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

export default MyForm;
Output
Page reloads immediately after alert, losing any React state or input data.
🔧

The Fix

To fix this, call event.preventDefault() inside your handleSubmit function. This stops the page from reloading and lets React handle the form submission smoothly.

jsx
import React from 'react';

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

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

export default MyForm;
Output
Alert shows and page does NOT reload, allowing React to manage form data.
🛡️

Prevention

Always include event.preventDefault() in your onSubmit handlers to stop unwanted page reloads. Use React hooks like useState to manage form inputs and keep your code clean. Enable linting rules that warn about missing preventDefault calls in event handlers.

⚠️

Related Errors

Common related errors include forgetting to bind the handler in class components (legacy) or trying to access form values without controlled inputs. Always use functional components with hooks and controlled inputs for best results.

Key Takeaways

Always call event.preventDefault() in onSubmit handlers to prevent page reload.
Use functional components and hooks to manage form state cleanly.
Attach the onSubmit handler directly to the
element, not buttons.
Lint your code to catch missing preventDefault calls early.
Avoid legacy class components and prefer modern React patterns.