← Back to Chapters

PreventDefault & StopPropagation

?️ PreventDefault & StopPropagation

⚛️ Introduction

In React, event handling follows the same principles as in the browser but uses the SyntheticEvent system for consistency. Two commonly used methods in event control are preventDefault() and stopPropagation().

These methods help you control the event flow — whether to stop a default browser action (like page reload) or to prevent events from bubbling up to parent elements.

? preventDefault()

The preventDefault() method stops the browser’s default action for a given event. It’s often used in forms, links, and buttons to prevent reloading or navigation.

? View Code Example
// Prevent form submission from reloading the page
function PreventFormReload() {
  const handleSubmit = (e) => {
    e.preventDefault(); // stops form submission and reload
    alert("Form submitted without reload!");
  };

  return (
    <form onSubmit={handleSubmit} className="p-3 border rounded w-50">
      <input className="form-control mb-2" placeholder="Enter your name" />
      <button className="btn btn-primary" type="submit">Submit</button>
    </form>
  );
}

Without e.preventDefault(), submitting a form would cause a full page reload — losing your React state.

? stopPropagation()

The stopPropagation() method prevents an event from bubbling up the DOM tree. This means parent elements won’t receive the same event.

? View Code Example
// Stop event from bubbling to parent element
function StopPropagationExample() {
  const handleParentClick = () => alert("Parent Clicked!");
  const handleChildClick = (e) => {
    e.stopPropagation(); // prevents parent event
    alert("Child Clicked!");
  };

  return (
    <div className="p-3 border border-dark" onClick={handleParentClick}>
      <p>Parent Div</p>
      <button className="btn btn-danger" onClick={handleChildClick}> Child Button </button>
    </div>
  );
}

Clicking the child button triggers only the child handler because stopPropagation() prevents the parent from being notified.

? Using Both Together

You can combine preventDefault() and stopPropagation() when you want to both stop default browser behavior and block event bubbling.

? View Code Example
// Prevent navigation and stop bubbling to parent
function CombinedExample() {
  const handleLinkClick = (e) => {
    e.preventDefault(); // stops navigation
    e.stopPropagation(); // stops bubbling
    alert("Link Click prevented and event stopped!");
  };

  return (
    <div onClick={() => alert("Parent Div Clicked!")}>
      <a href="https://react.dev" onClick={handleLinkClick}> Visit React Docs </a>
    </div>
  );
}

In this example, clicking the link neither opens the React website nor triggers the parent click alert.

? Event Bubbling in React

React handles events using event delegation — a single event listener is attached to the document root. When an event occurs, it bubbles up through the component tree unless stopPropagation() is called.

Understanding event bubbling is crucial when building nested UI structures like modals, dropdowns, and menus.

? Real-World Example

Consider a modal where clicking outside should close it, but clicking inside should not. This can be handled using stopPropagation():

? View Code Example
// Modal that closes on outside click but not when clicking inside
function ModalExample({ close }) {
  return (
    <div className="modal-overlay" onClick={close} style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, backgroundColor: "rgba(0,0,0,0.3)", display: "flex", justifyContent: "center", alignItems: "center" }}>
      // clicking outside closes modal
      <div className="modal-content p-3 bg-white rounded" onClick={(e) => e.stopPropagation()}>
        // prevent close when clicking inside
        <h5>Modal Window</h5>
        <p>Clicking inside will not close this modal.</p>
        <button className="btn btn-danger" onClick={close}>Close</button>
      </div>
    </div>
  );
}

? Tips

  • Use preventDefault() for forms, links, and inputs to stop unwanted browser actions.
  • Use stopPropagation() to isolate child event logic from parent components.
  • Be careful — overusing stopPropagation() can make debugging complex UIs harder.
  • In nested clickable elements, always check if both parent and child need event handling.

? Try This

  1. Create a form and use preventDefault() to stop reload while logging the form input value.
  2. Build a nested div and button structure, experiment with and without stopPropagation().
  3. Add a link that doesn’t navigate but triggers a custom message using both methods.
  4. Simulate a modal that closes on outside clicks but stays open when clicked inside.

Goal: Learn how to control browser behavior and event flow using preventDefault() and stopPropagation() for cleaner, predictable React interactions.