In traditional React, a component's JSX markup is rendered directly inside its parent DOM element in the tree.
Normally, this is desirable. However, when building Modals, Tooltips, Dropdowns, and Toast Notifications, standard DOM hierarchy creates severe layout bugs:
overflow: hidden Clipping: If any ancestor container in the tree has overflow: hidden or overflow: scroll, any modal or tooltip extending beyond the parent container's boundaries will be harshly clipped and cut off!z-index Stacking Context Collisions: Even if you set z-index: 999999 on a modal, if its parent container is trapped in a lower stacking context (z-index: 1), the modal will stay buried beneath other elements on the page!createPortal?React Portals provide a first-class way to render children into a different DOM node that exists entirely outside the DOM hierarchy of the parent component.
With a portal, your component can live logically in the React component tree (sharing props, state, and context), while its physical HTML DOM nodes are injected directly into document.body or a dedicated <div id="modal-root">.
$$\text{ReactDOM.createPortal}(\text{children}, \text{domNode})$$
In your index.html, declare a designated portal target right after the root:
In your React component, use createPortal from react-dom:
overflow: hidden: Because the DOM node is attached directly to #portal-root at the document root, no ancestor containers can clip its boundaries.createPortal be imported from?createPortal(children, domNode)?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Reporting Client Errors to Monitoring Services | Building Modal Dialogs and Overlays with Portals |
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.