0
0
Reactframework~5 mins

Preventing default behavior in React

Choose your learning style9 modes available
Introduction

Sometimes, when you click a link or submit a form, the browser does something automatically. Preventing default behavior stops that automatic action so you can control what happens next.

You want to stop a link from opening a new page and instead show a popup.
You want to handle form submission with JavaScript without refreshing the page.
You want to stop a button inside a form from submitting the form automatically.
You want to prevent a checkbox from toggling under certain conditions.
Syntax
React
function handleEvent(event) {
  event.preventDefault();
  // your code here
}

The event object is passed automatically to event handlers in React.

Calling event.preventDefault() stops the browser's default action for that event.

Examples
This stops a link from navigating to a new page and shows an alert instead.
React
function handleClick(event) {
  event.preventDefault();
  alert('Link clicked but no page change!');
}
This prevents the form from reloading the page on submit.
React
function handleSubmit(event) {
  event.preventDefault();
  console.log('Form submitted without page reload');
}
Sample Program

This React component shows a link and a form. Clicking the link or submitting the form will not trigger the browser's default actions. Instead, alerts appear to confirm the events were caught and handled.

Accessibility is considered by adding an aria-label to the link. The layout uses semantic HTML and spacing for clarity.

React
import React from 'react';

export default function PreventDefaultExample() {
  function handleLinkClick(event) {
    event.preventDefault();
    alert('You clicked the link, but no page change!');
  }

  function handleFormSubmit(event) {
    event.preventDefault();
    alert('Form submitted without reload!');
  }

  return (
    <main>
      <h1>Prevent Default Behavior Example</h1>
      <a href="https://example.com" onClick={handleLinkClick} aria-label="Example link">Example Link</a>
      <form onSubmit={handleFormSubmit} style={{ marginTop: '1rem' }}>
        <button type="submit">Submit Form</button>
      </form>
    </main>
  );
}
OutputSuccess
Important Notes

Always pass the event object to your handler to use preventDefault().

Preventing default behavior is useful to create custom interactions without page reloads or navigation.

Summary

Use event.preventDefault() to stop the browser's automatic action.

This lets you control what happens when users click links or submit forms.

It helps create smoother, interactive web apps without page reloads.