React Portals – Complete Detailed Notes
React Portals are a React feature that allows you to render elements into a different part of the DOM tree while keeping them connected to the same React component tree. They are commonly used to build modal dialogs, popups, tooltips, dropdown overlays, and notification panels.
1. What Are React Portals?
A React Portal allows a component to render its children into a DOM node that exists outside its normal parent DOM hierarchy. Although the elements appear in a different location in the DOM, they continue to behave like children of the component that created the portal in the React tree.
React provides the createPortal() function from the react-dom package to create portals.
Basic Syntax
import { createPortal } from "react-dom";
createPortal(children, domNode, key);
- children: The JSX, component, or other renderable React content to display.
- domNode: The existing DOM element where the portal content should appear.
- key: An optional unique string or number used to identify the portal when rendering collections.
The destination DOM node must already exist when it is passed to createPortal().
2. Why Do We Use React Portals?
In some applications, a component needs to display content outside its normal visual container. For example, a modal dialog may be hidden or clipped because a parent element uses overflow: hidden. A portal allows the dialog to be rendered elsewhere in the DOM.
Common Use Cases
- Modal dialogs: Display login forms, confirmation dialogs, and other overlays.
- Tooltips: Show contextual information outside a component's normal container.
- Dropdown menus: Display menus that might otherwise be clipped by parent containers.
- Notifications: Render toast messages in a dedicated notification area.
- Popups: Display floating content above other interface elements.
- Third-party integrations: Render React components into DOM elements managed by another library.
3. How React Portals Work
Normally, React renders a component's elements inside the DOM node associated with its parent. With a portal, React places selected content inside another DOM node.
Normal Rendering
<div id="root">
<div class="app">
<h2>Main Application</h2>
<div class="modal">Modal Content</div>
</div>
</div>
In this example, the modal is rendered inside the application container.
Rendering with a Portal
<body>
<div id="root">
<div class="app">
<h2>Main Application</h2>
</div>
</div>
<div id="portal-root">
<div class="modal">Modal Content</div>
</div>
</body>
With a portal, the modal content appears inside portal-root, outside the application's regular DOM container. It still belongs to the same React tree.
4. Creating a React Portal
Follow these steps to create a basic portal in a React application.
Step 1: Create a Portal Container
Add a destination element to your application's HTML file.
<div id="root"></div>
<div id="portal-root"></div>
Step 2: Import createPortal
Import the function from the react-dom package.
import { createPortal } from "react-dom";
Step 3: Create a Component
Use createPortal() to render the content into the destination element.
import { createPortal } from "react-dom";
function MyPortal() {
const portalRoot = document.getElementById("portal-root");
if (!portalRoot) {
return null;
}
return createPortal(
<h2>Hello from React Portal!</h2>,
portalRoot
);
}
export default MyPortal;
Step 4: Use the Component
import MyPortal from "./MyPortal";
function App() {
return (
<div>
<h1>Main Application</h1>
<MyPortal />
</div>
);
}
export default App;
Result: The heading from MyPortal appears inside the portal-root element rather than inside the main application container.
5. Building a Modal Using React Portals
A modal is one of the most common uses of React Portals. It displays important information or a form above the main page content.
Modal Component
import { createPortal } from "react-dom";
function Modal({ onClose }) {
const portalRoot = document.getElementById("portal-root");
if (!portalRoot) {
return null;
}
return createPortal(
<div className="modal-overlay">
<div
className="modal-content"
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
>
<h2 id="modal-title">Welcome to React</h2>
<p>This modal is rendered using a portal.</p>
<button onClick={onClose}>Close</button>
</div>
</div>,
portalRoot
);
}
export default Modal;
App Component
import { useState } from "react";
import Modal from "./Modal";
function App() {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<h1>React Portal Example</h1>
<button onClick={() => setIsOpen(true)}>
Open Modal
</button>
{isOpen && (
<Modal onClose={() => setIsOpen(false)} />
)}
</div>
);
}
export default App;
CSS Styling
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 24px;
border-radius: 10px;
max-width: 420px;
width: calc(100% - 40px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}
How it works:
- The user clicks the Open Modal button.
- The
isOpen state becomes true.
- React renders the Modal component.
createPortal() places the modal in the portal-root element.
- Clicking Close calls the callback and updates the state to
false.
- The modal is removed from the rendered output.
6. React Portals and Event Bubbling
One important feature of portals is that events propagate according to the React component tree rather than only following the physical DOM structure.
For example, a click inside a portal can trigger an event handler on a React parent component, even if the portal's DOM element is located elsewhere in the document.
Example
import { createPortal } from "react-dom";
function PortalButton() {
return createPortal(
<button>Click Portal Button</button>,
document.body
);
}
function App() {
return (
<div onClick={() => console.log("Parent clicked")}>
<h2>Portal Event Example</h2>
<PortalButton />
</div>
);
}
export default App;
When the portal button is clicked, the parent's React click handler can run because the portal remains part of the same React tree.
Preventing Event Propagation
If you do not want an event to reach a parent handler, you can stop its propagation where appropriate.
<button
onClick={(event) => {
event.stopPropagation();
console.log("Portal button clicked");
}}
>
Click Me
</button>
Use stopPropagation() carefully because it changes normal event handling behavior.
7. React Portals vs. Normal Rendering
| Feature |
Normal Rendering |
Portal Rendering |
| DOM placement |
Inside the normal parent DOM hierarchy |
Inside a specified destination DOM node |
| React component tree |
Maintains the usual parent-child relationship |
Remains connected to the component that created it |
| Event bubbling |
Follows React tree behavior |
Also follows React tree behavior |
| Common uses |
Page content, forms, cards, layouts |
Modals, tooltips, overlays, notifications |
| Destination |
Determined by normal DOM rendering |
Specified using a DOM node |
8. React Portals vs. React Fragments
React Portals and React Fragments serve different purposes. A Fragment groups elements without creating an extra DOM node, while a Portal renders elements into a different DOM location.
| Feature |
React Fragment |
React Portal |
| Purpose |
Group multiple elements |
Render content in another DOM location |
| Extra wrapper element |
No |
No wrapper is created by the portal itself |
| Changes physical DOM placement |
No |
Yes |
| API |
Fragment or <>...</> |
createPortal() |
| Typical use case |
Grouping headings and paragraphs |
Displaying a modal outside its normal container |
9. Advantages of React Portals
- Flexible DOM placement: Content can appear outside its normal parent container.
- Better overlay design: Useful for modals, popups, and tooltips.
- Reduced clipping problems: Can avoid clipping caused by ancestor containers with styles such as
overflow: hidden.
- React context support: Portal children can access context provided by their React ancestors.
- React event behavior: Events continue to follow the React tree.
- Reusable components: Portal-based modal and notification components can be reused throughout an application.
10. Limitations and Important Considerations
- Destination must exist: The target DOM node must be available when passed to
createPortal().
- Accessibility: Modals should support appropriate keyboard navigation, focus management, accessible names, and dismissal behavior.
- Event propagation: Events can reach React ancestors unexpectedly if the component structure is not considered.
- Styling: Portal content may need separate CSS rules because it is physically located elsewhere in the DOM.
- Cleanup: React manages the portal content, but any external DOM nodes or event listeners created manually must be cleaned up appropriately.
- Server rendering: Code that accesses browser globals such as
document must be designed carefully when using server-side rendering.
11. Common Mistakes When Using React Portals
Mistake 1: Using a Non-Existent Container
const portalRoot = document.getElementById("missing-root");
return createPortal(<p>Hello</p>, portalRoot);
Problem: The destination element does not exist, so the portal cannot be created with that value.
Solution: Make sure the destination exists and handle a missing node when necessary.
const portalRoot = document.getElementById("portal-root");
if (!portalRoot) {
return null;
}
return createPortal(<p>Hello</p>, portalRoot);
Mistake 2: Assuming a Portal Creates a New React Root
A portal does not create a separate React root. It moves the physical DOM placement of its children while preserving their connection to the original React tree.
Mistake 3: Ignoring Modal Accessibility
A modal should manage keyboard focus appropriately, have an accessible name, and provide a clear way to close it. For a complete modal, consider Escape-key handling, focus trapping, focus restoration, and suitable ARIA attributes.
Mistake 4: Assuming Portals Automatically Fix Every Layering Issue
Portals can help avoid ancestor clipping and stacking-context issues, but they do not automatically solve every positioning or z-index problem. The portal's destination and CSS still matter.
12. Practical Project: Notification Portal
Create a notification component that displays a message outside the main application container.
Notification Component
import { createPortal } from "react-dom";
function Notification({ message }) {
const portalRoot = document.getElementById("portal-root");
if (!portalRoot) {
return null;
}
return createPortal(
<div className="notification" role="status">
{message}
</div>,
portalRoot
);
}
export default Notification;
App Component
import Notification from "./Notification";
function App() {
return (
<div>
<h1>Dashboard</h1>
<p>Your main application content appears here.</p>
<Notification message="Your profile was saved successfully!" />
</div>
);
}
export default App;
CSS
.notification {
position: fixed;
top: 20px;
right: 20px;
background: #e6f7e9;
color: #185c2b;
padding: 14px 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 1100;
}
Expected result: The notification appears near the top-right corner of the browser window, even though the Notification component is declared inside the main React application.
13. React Portals Interview Questions and Answers
Q1. What is a React Portal?
A React Portal lets you render children into a DOM node outside the normal DOM hierarchy of the component that creates them.
Q2. Which function is used to create a portal?
The createPortal() function imported from react-dom.
Q3. What are the main arguments of createPortal()?
It accepts the renderable children, an existing destination DOM node, and an optional key.
Q4. What are the common use cases of portals?
Common uses include modal dialogs, tooltips, dropdown overlays, notifications, and content rendered inside third-party DOM containers.
Q5. Do portals preserve React context?
Yes. Portal children can access context provided by their React ancestors.
Q6. How do events bubble through portals?
Events propagate according to the React tree rather than only according to the physical DOM hierarchy.
Q7. What is the difference between a portal and a separate React root?
A portal remains part of its existing React tree. A separate root is created with createRoot() and is managed independently.
Q8. Can portals help with CSS overflow problems?
Yes. Rendering an overlay outside an ancestor with overflow: hidden can prevent that ancestor from clipping the overlay.
Q9. Do portals automatically handle accessibility?
No. Developers must implement suitable keyboard interaction, focus management, accessible labels, and other requirements.
Q10. Can a portal render into any DOM element?
It can render into an appropriate existing DOM node, provided that the node is valid and available when passed to createPortal().
14. Best Practices for React Portals
- Use portals when content needs to appear outside its normal DOM container.
- Create a dedicated destination element for overlays when appropriate.
- Keep portal components reusable and easy to maintain.
- Handle cases where the target DOM node is unavailable.
- Manage modal focus, keyboard interactions, and accessibility carefully.
- Understand React event bubbling before adding parent event handlers.
- Use CSS positioning and stacking order intentionally.
- Clean up manually created DOM resources and event listeners when necessary.
15. Quick Revision Checklist
- Understand the meaning and purpose of React Portals.
- Know the syntax and arguments of
createPortal().
- Learn how to create a portal container in HTML.
- Practice building a modal and notification component.
- Understand event bubbling through portals.
- Know the difference between React Portals and Fragments.
- Remember accessibility and browser-rendering considerations.
16. Official React Documentation
Read the official documentation for a deeper explanation, examples, and important caveats.
17. React JS Training at JustAcademy
Learn React JS concepts, component development, JSX, props, state, hooks, portals, and practical application development through React JS training.
Explore JustAcademy React JS Training
Want to understand the course structure and training approach? Register for a course demo.
Register for React JS Course Demo
Conclusion
React Portals make it possible to render content into a different DOM location without disconnecting it from the original React component tree. They are especially useful for modals, tooltips, dropdowns, and notifications. By understanding createPortal(), event propagation, destination elements, and accessibility requirements, you can build more flexible and maintainable React applications.