πŸ”„ React Optimization & Advanced Concepts
Estimated reading: 4 minutes 41 views

🧱 React Portals – Render Components Outside the DOM Hierarchy (2025 Guide)


🧲 Introduction – What Are React Portals?

In React.js, components are rendered within the DOM tree of their parent. But what if you need to render a modal, tooltip, or dropdown that needs to appear outside this DOM hierarchy?

Enter React Portals β€” a powerful feature that lets you render a component into a different part of the DOM, outside the root hierarchy.

🎯 In this guide, you’ll learn:

  • What React Portals are and when to use them
  • How to create and render a portal
  • Real-world use cases like modals and tooltips
  • Best practices and accessibility tips

πŸ“¦ 1. What is a React Portal?

A portal allows you to render a child component into a DOM node that exists outside the parent component’s DOM hierarchy.

βœ… Syntax:

ReactDOM.createPortal(child, container)
  • child: JSX to render
  • container: DOM node to render into (outside root)

πŸ› οΈ 2. How to Use React Portals

βœ… Step 1: Add a DOM container to index.html

<body>
  <div id="root"></div>
  <div id="portal-root"></div>
</body>

βœ… Step 2: Render into the portal

import { createPortal } from 'react-dom';

function Modal({ children }) {
  const portalRoot = document.getElementById('portal-root');
  return createPortal(
    <div className="modal">{children}</div>,
    portalRoot
  );
}

βœ… Usage:

function App() {
  return (
    <>
      <h1>Main App</h1>
      <Modal>
        <p>This modal is rendered via Portal!</p>
      </Modal>
    </>
  );
}

πŸ“˜ The modal appears outside the #root DOM tree
βœ… Useful for z-index management, scroll isolation, and full-screen overlays


🎯 3. Common Use Cases for Portals

Use CaseWhy Portals Help
πŸͺŸ ModalsEscape overflow: hidden of parents
πŸ’¬ TooltipsPosition relative to screen, not container
πŸ“„ DropdownsPrevent clipping and overflow issues
πŸ“Œ Toasts/AlertsFixed positioning outside layout flow
πŸ“Ž Context menusIndependent of parent structure

🎨 4. Styled Modal Example with Close Button

function Modal({ children, onClose }) {
  return createPortal(
    <div className="backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button onClick={onClose}>Close</button>
        {children}
      </div>
    </div>,
    document.getElementById('portal-root')
  );
}

βœ… Usage in App:

{isOpen && <Modal onClose={() => setIsOpen(false)}>Hello from portal!</Modal>}

πŸ“˜ Click outside to close, stop propagation inside


⚠️ 5. Portals & Accessibility

βœ… Add ARIA attributes for modals and dialogs:

<div role="dialog" aria-modal="true" aria-labelledby="modal-title">
  <h2 id="modal-title">Modal Title</h2>
  ...
</div>

βœ… Trap focus with libraries like focus-trap-react
βœ… Return focus to triggering element after close


🧠 6. Portals in React DevTools

By default, portal-rendered components still appear under their parent in React DevTools, even though they exist outside in the DOM. This keeps component structure intuitive and debuggable.


πŸ“˜ Best Practices

βœ… Use portals for components that require DOM isolation
βœ… Handle escape key and outside clicks for modals
βœ… Keep your portal root (#portal-root) outside #root
βœ… Clean up any event listeners or side effects on unmount
βœ… Use context or props to pass data into portal components


πŸ“Œ Summary – Recap & Next Steps

React Portals are essential for building overlays, modals, and UI elements that need to live outside the normal DOM hierarchy. They improve flexibility without compromising component logic.

πŸ” Key Takeaways:

  • createPortal(child, container) renders outside the DOM tree
  • Ideal for modals, toasts, tooltips, and dropdowns
  • Maintain event bubbling and component logic
  • Use with accessibility standards for keyboard and screen readers

βš™οΈ Real-World Relevance:
Used in apps like Slack, Notion, and Stripe for popups, modals, tooltips, and notifications.


❓ FAQ Section

❓ What is the purpose of React Portals?
βœ… To render content into a different part of the DOMβ€”outside the root treeβ€”while maintaining React’s virtual DOM hierarchy.


❓ Do Portals break event propagation?
❌ No. Events still propagate through the React tree as if the component was rendered inside the parent.


❓ Can I use multiple portal roots?
βœ… Yes. You can create and use multiple DOM nodes and target them as needed.


❓ Do Portals affect styling?
βœ… Portals bypass container styles like overflow: hidden, making them ideal for modals or dropdowns that require absolute positioning.


❓ Are React Portals supported in all browsers?
βœ… Yes. Portals are supported in all modern browsers and have been stable since React 16.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧱 React Portals – Rendering Outside DOM

Or Copy Link

CONTENTS
Scroll to Top