REACT EVENTS /// PREVENT DEFAULT /// STOP PROPAGATION /// BUBBLING /// SYNTHETIC EVENTS /// REACT EVENTS /// PREVENT DEFAULT /// STOP PROPAGATION ///

React Prevent

Mastering the Event Flow in Modern Apps

ReactPrevent.js
1 / 7
1
2
3
4
5
6
🛡️

ADA: In React, many elements have default browser behaviors. For example, a form refreshes the page on submit, and a link navigates away. We use event.preventDefault() to stop this.

A.D.A

Event Logic Processor

Ready to stop some default behaviors?

Challenge Mode

Can you prevent a form from submitting while also stopping the click from bubbling to the background? Try it in the mission below.

Controlling the DOM Cascade in React

"In React, we are building a declarative UI, but the underlying browser still wants to do things its own way. Mastery of event prevention is the bridge between browser defaults and custom logic."

1. The Default Submission Problem

HTML forms have been refreshing pages since 1993. In a modern SPA (Single Page Application), we want to avoid this at all costs. When you use onSubmit, React passes a SyntheticEvent to your handler. Calling e.preventDefault() tells the browser: "I've got this, don't reload the window."

2. Bubbling and StopPropagation

Imagine a 'Delete' button inside a 'Card' component. If both have click handlers, clicking the button will trigger both. This is often unintended. e.stopPropagation() effectively creates a barrier, ensuring that the event doesn't travel further up the tree.

Pro Tip: React 17+ attaches event listeners to the root container, not the document. This makes e.stopPropagation() more predictable when mixing React with non-React code.

Event Mastery Glossary

SyntheticEvent

A cross-browser wrapper around the browser’s native event. It has the same interface as native events, including stopPropagation() and preventDefault().

onClick={(e) => console.log(e)}

Event Bubbling

A type of event propagation where the event fires on the element, then bubbles up through its ancestors.

Parent(div) <- Child(button)

preventDefault()

Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

e.preventDefault()

stopPropagation()

Prevents further propagation of the current event in the bubbling and capturing phases.

e.stopPropagation()

onSubmit

The React event handler for form submissions, which triggers page refresh by default.

<form onSubmit={...}>