Portals
Portals
React Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
The Problem
Usually, when you render a component in React, it is mounted into the DOM as a direct child of its parent element.
// React Code
function Parent() {
return <div className="parent"><Child /></div>;
}
// Resulting HTML
<div class="parent">
<div class="child"></div>
</div>
This structural strictness creates problems for elements that need to visually “break out” of their container, such as Modals, Tooltips, and Dropdown Menus.
If a Parent component has overflow: hidden or a complex z-index context, a Child modal inside it will be clipped or hidden behind other elements on the page.
The Portal Solution
A Portal allows you to keep the component in the same logical position within the React component tree (it can still access Context and Props from its parents), while physically inserting its HTML into a completely different part of the DOM document (usually document.body).
How to use createPortal
You use the createPortal function from react-dom.
import { createPortal } from 'react-dom';
function Modal({ children, isOpen }) {
if (!isOpen) return null;
// Instead of returning JSX directly, return createPortal(jsx, targetNode)
return createPortal(
<div className="modal-overlay">
<div className="modal-content">
{children}
</div>
</div>,
document.body // The target DOM node where this HTML will be injected
);
}
Now, no matter where you use <Modal> in your React tree, its HTML will be appended to the very end of the <body> tag, guaranteeing that it overlays all other content and escapes any overflow: hidden containers.
Event Bubbling in Portals
One of the most powerful features of Portals is that React events still bubble up the React tree, regardless of where the node is in the DOM tree.
function App() {
// Even though the Modal is rendered in document.body,
// clicks inside the Modal will still bubble up to this div!
return (
<div onClick={() => console.log('App clicked!')}>
<h1>My App</h1>
<Modal isOpen={true}>
<button>Click me</button>
</Modal>
</div>
);
}
If the user clicks the <button> inside the Modal, the event will bubble up through the React virtual DOM tree, hitting the div in App, and logging “App clicked!”.
This allows you to create global event listeners (like clicking outside a dropdown to close it) very easily without worrying about the physical DOM structure.
Interview Questions
Q: What are React Portals used for?
A: Portals allow you to render children into a completely different part of the actual HTML DOM (like appending directly to document.body) outside of the parent component’s DOM hierarchy. This is essential for modals, tooltips, and dropdowns, allowing them to escape CSS overflow: hidden and z-index traps while still remaining securely inside the React Virtual DOM tree.