Clean β’ Professional
React Portals provide a way to render children into a different part of the DOM β outside of the parent componentβs hierarchy β without breaking Reactβs data flow or event handling. You can think of a Portal as a βteleportβ for React elements β it allows a component to visually appear somewhere else in the DOM, but logically remain connected to its parent component.
Portals are most useful when you need to render UI elements that must appear above other elements or outside normal layout flow, such as:
For example, a modal should appear above all content and not be affected by CSS overflow or z-index limitations of its parent container.
Normally, React components render inside the DOM node defined by your appβs root (e.g., #root).
With portals, you can render components inside another DOM node, such as #modal-root.
Syntax
ReactDOM.createPortal(child, container)
child β The React element to render.container β The DOM node where the element should be mounted.Step 1: Create a modal root in index.html
<body>
<div id="root"></div>
<div id="modal-root"></div> <!-- Portal target -->
</body>
Step 2: Create a Modal component
import React from "react";
import ReactDOM from "react-dom";
function Modal({ children }) {
const modalRoot = document.getElementById("modal-root");
return ReactDOM.createPortal(
<div className="modal-overlay">
<div className="modal-content">{children}</div>
</div>,
modalRoot
);
}
export default Modal;
Step 3: Use the Modal component
import React, { useState } from "react";
import Modal from "./Modal";
function App() {
const [open, setOpen] = useState(false);
return (
<div>
<h1>React Portal Example</h1>
<button onClick={() => setOpen(true)}>Open Modal</button>
{open && (
<Modal>
<h2>Hello from the Portal!</h2>
<button onClick={() => setOpen(false)}>Close</button>
</Modal>
)}
</div>
);
}
export default App;
#modal-root).open state in App.One of the best things about Portals is that events still propagate normally through the React tree. That means even if your modal is rendered outside the root DOM, event handlers in parent components will still work as expected.
| Feature | Description |
|---|---|
| Purpose | Render React elements outside the root DOM node |
| Method | ReactDOM.createPortal(child, container) |
| Common Uses | Modals, tooltips, dropdowns, popups |
| Benefits | Avoids layout issues, keeps React tree intact, supports event bubbling |