Resolving Event Propagation Issues When Using React with Swiper
Key point
This article analyzes why stopPropagation fails when using Swiper alongside React due to React's event delegation structure and presents three solutions.
Details
When using React alongside external libraries like Swiper, the stopPropagation method on child elements may fail to prevent event handlers on parent elements. This occurs because React delegates event listeners to the React root element rather than the actual DOM elements.
Differences in Event Propagation Order
Swiper internally detects the browser's touchend event and triggers its own click event. If a developer registers a click handler directly on a Swiper element using addEventListener, this listener attaches to that specific element in the actual DOM tree. In contrast, React's onClick is registered on the React root.
During the bubbling phase, the event propagates from the actual DOM element toward the React root. Therefore, the listener attached directly to the Swiper element executes first, followed by the listener for the button attached to the React root. In this process, the button's stopPropagation cannot reverse the already-executed Swiper handler.
Solutions
- Use the Capture Phase: Handling events in the capture phase can change the execution order, but this is not recommended as it may cause unexpected side effects in complex view structures.
- Register Listeners Directly on DOM Elements: Use
useRefanduseEffectto registeraddEventListenerdirectly on the rendered button element. In this case, both listeners attach to the actual DOM element, sostopPropagationworks correctly. - Wrap with a React Element: Add
onClickto a parentdivwrapping the Swiper component. Leveraging React's event delegation structure allows for natural control of event propagation, making this the most intuitive method from a maintenance perspective.
This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.
Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.