Intermediate LevelReact JS & React 19
Why do events from a React Portal bubble up to the React parent instead of the DOM parent?
❓ Interview Prompt: Explain React Portals (`createPortal`), rendering nodes outside root DOM, Virtual DOM event bubbling vs Real DOM hierarchy.
React Portals ('createPortal(children, domNode)') render child DOM nodes into a different location in the physical DOM tree (e.g. appending a modal to 'document.body'):
The Event Bubbling Quirk:
Even though a portal element is located elsewhere in the physical HTML DOM tree, events fired inside a portal bubble up through the React Virtual DOM hierarchy to its parent React component! A click inside a portal modal triggers 'onClick' on its React parent container.
Code Implementation Example
jsx
import { createPortal } from 'react-dom';
function Modal({ children }) {
// Physical DOM node is document.body
return createPortal(
<div className="modal-overlay">{children}</div>,
document.body
);
}
function ParentApp() {
// Clicks inside Modal trigger handleClick due to React Virtual DOM event bubbling!
return (
<div onClick={() => console.log('Parent caught event!')}>
<Modal><button>Click Me</button></Modal>
</div>
);
}💡React Virtual DOM event bubbling passing through Portals.
🎯 Interview Key Takeaway
Events inside React Portals bubble up through the React Virtual DOM parent component tree, regardless of physical DOM location.
#Portals#createPortal#Event Bubbling#Intermediate
Back to all React JS & React 19 Questions→