One of the most fascinating aspects of React Portals is how events behave:
Consider this scenario:
In the physical HTML DOM:
<button> is a direct child of <body>.<ParentDiv> is located deep inside <div id="root">.<button> is NOT inside <ParentDiv>.Yet, if you click the <button>: handleParentClick on <ParentDiv> WILL FIRE!
React does not rely on native DOM event listeners attached to individual elements.
As explored in our SyntheticEvent architecture lessons:
<div id="root">).<ChildWithPortal> is a logical child of <ParentDiv> in the React tree, React bubbles the SyntheticEvent up through the component hierarchy as expected!If your portal represents a modal or tooltip and you do not want its internal click events to trigger parent container handlers:
e.stopPropagation() inside your portal event handler!createPortal?<Parent onClick={handleClick}> renders a portal that attaches a <button> to document.body, what happens when that button is clicked?document.addEventListener('click'), will it receive portal clicks?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Building Modal Dialogs and Overlays with Portals | Component Composition as an Alternative to Context |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.