0
0
ReactDebug / FixBeginner · 3 min read

How to Prevent Default Behavior in React Events

In React, you prevent the default browser behavior by calling event.preventDefault() inside your event handler function. This stops actions like form submission or link navigation from happening automatically.
🔍

Why This Happens

By default, some HTML elements like forms and links perform actions automatically when interacted with. For example, submitting a form reloads the page. React event handlers receive an event object, but if you don't stop the default behavior, the browser will still do its usual action.

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
When clicking the Submit button, the alert shows but then the page reloads immediately.
🔧

The Fix

To stop the page from reloading, call event.preventDefault() inside the event handler. This tells the browser not to perform its default action, so you can control what happens next.

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
Clicking Submit shows the alert and the page does NOT reload.
🛡️

Prevention

Always use event.preventDefault() in React event handlers when you want to stop the browser's default behavior. This is common with forms, links, and drag-and-drop events. Use linting tools like ESLint with React plugin to warn if you forget to prevent defaults where needed.

Also, name your event parameter clearly (like event or e) and call preventDefault() early in the handler to avoid unexpected behavior.

⚠️

Related Errors

Sometimes developers forget to pass the event object to the handler or try to call preventDefault() outside the event context, causing errors like Cannot read property 'preventDefault' of undefined. Always ensure your handler receives the event parameter.

Also, using href="#" on links without preventing default can cause unwanted page jumps. Use event.preventDefault() or better semantic elements.

Key Takeaways

Use event.preventDefault() inside React event handlers to stop default browser actions.
Always pass the event object to your handler functions to access preventDefault().
Call preventDefault() early in the handler to avoid unwanted page reloads or navigation.
Use linting tools to catch missing preventDefault() calls in event handlers.
Remember to handle default behavior for forms, links, and other interactive elements.