Repository navigation
Portals
vinibiavatti1 edited this page Sep 28, 2026
·
4 revisions
Portals provide a way to render a child component into a DOM node that exists outside the parent component's DOM hierarchy (i.e. <div id="portal-root"></div>). This is particularly useful for UI overlays like modals, tooltips, slide-overs, or notifications that need to break out of parent container styles (overflow: hidden or z-index stacking contexts).
Note: Despite being rendered into a different location in the DOM tree, portals behave like standard React children in every other way, preserving event bubbling and context access.
import { createPortal } from 'react-dom';
// The second argument defines where the JSX should be rendered in the DOM
export const Modal = ({ message }) => {
return createPortal(
<div className="modal">{message}</div>,
document.getElementById('portal-root')
);
};To make this work, ensure you have a dedicated target container (such as a portal-root div) placed right alongside your main root node in your index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React Handbook</title>
</head>
<body>
<!-- Main React root container -->
<div id="root"></div>
<!-- Dedicated container for modals, tooltips, and overlays -->
<div id="portal-root"></div>
<!-- Main JavaScript entry point bundle -->
<script type="module" src="/src/Main.jsx"></script>
</body>
</html>- Home
- Functional Components
- Props
- Fragments
- Memoization
- Forward Ref
- Portals
- Suspense
-
Hooks
- State
- Context
- Effect
- Ref
- Performance
- Concurrent
- Form
- Utility
- Custom Hooks