REACT

React Portal: Syntax, Usage, and Examples

React portals let you render components outside their parent DOM hierarchy while keeping them part of the React tree. This approach is useful when elements like modals, tooltips, pop-ups, or dropdowns need to appear outside a container that has overflow: hidden or z-index restrictions.

How to Use React Portal

React provides the createPortal() function to move a component's rendered output to a different DOM node without breaking React's reactivity.

Basic Syntax

import React from "react";
import ReactDOM from "react-dom";

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

In this example, the Modal component renders into #modal-root, even if it is used inside another component.

Setting Up a Portal Target in HTML

A portal needs a designated target in the HTML file.

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

Without this target, the portal will not work correctly.

When to Use React Portal

Modals and Dialogs

Portals allow modals to escape their parent’s constraints, ensuring they are not clipped by overflow: hidden or positioned incorrectly due to z-index issues.

import React, { useState } from "react";
import ReactDOM from "react-dom";

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

function App() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsOpen(true)}>Open Modal</button>
      {isOpen && <Modal onClose={() => setIsOpen(false)}>This is a modal.</Modal>}
    </div>
  );
}

Tooltips and Pop-ups

Tooltips need to appear outside their parent container while being positioned relative to another element.

import React from "react";
import ReactDOM from "react-dom";

function Tooltip({ text, position }) {
  return ReactDOM.createPortal(
    <div className="tooltip" style={{ top: position.top, left: position.left }}>
      {text}
    </div>,
    document.getElementById("tooltip-root")
  );
}

Context Menus

A right-click menu should not be confined by the parent component's layout. Using a portal helps position it freely.

import React, { useState } from "react";
import ReactDOM from "react-dom";

function ContextMenu({ position, onClose }) {
  return ReactDOM.createPortal(
    <ul className="context-menu" style={{ top: position.y, left: position.x }}>
      <li>Option 1</li>
      <li>Option 2</li>
      <li onClick={onClose}>Close</li>
    </ul>,
    document.getElementById("context-menu-root")
  );
}

function App() {
  const [menuPosition, setMenuPosition] = useState(null);

  const handleRightClick = (event) => {
    event.preventDefault();
    setMenuPosition({ x: event.clientX, y: event.clientY });
  };

  return (
    <div onContextMenu={handleRightClick}>
      <h1>Right-click to open the context menu</h1>
      {menuPosition && <ContextMenu position={menuPosition} onClose={() => setMenuPosition(null)} />}
    </div>
  );
}

Learn More About React Portal

React Portal vs. Normal Rendering

A normal React component renders inside its parent’s DOM hierarchy. This behavior can cause unwanted clipping or layout issues when an element needs to break free from constraints like overflow: hidden. React portals solve this by rendering the element in a different DOM location while preserving its React state and event handling.

Creating a React Portal Component

You can wrap portal logic inside a reusable component for consistent behavior across an application.

function Portal({ children, targetId }) {
  const targetElement = document.getElementById(targetId);
  return targetElement ? ReactDOM.createPortal(children, targetElement) : null;
}

// Usage
<Portal targetId="modal-root">
  <p>This content is rendered in a portal.</p>
</Portal>

Event Bubbling with Portals

Even though a portal renders outside the parent component’s DOM structure, events still bubble up through the React tree. If you want to stop an event from propagating, call event.stopPropagation().

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

Using React Portal in Functional Components

Portals work the same way in functional components as they do in class components. The createPortal() function behaves identically in both cases.

const MyPortalComponent = ({ children }) => {
  return ReactDOM.createPortal(children, document.getElementById("portal-root"));
};

Creating a Portal in React Native

React Native does not have createPortal(), but you can achieve similar behavior with the react-native-portalize package.

import { Portal } from "react-native-portalize";

function App() {
  return (
    <Portal>
      <Text>This is inside a portal in React Native.</Text>
    </Portal>
  );
}

Using Portals with Iframes

If you need to render content inside an iframe while keeping it in the React tree, use a portal with an iframe reference.

function IframePortal({ children }) {
  const iframeRef = React.useRef(null);

  return (
    <iframe ref={iframeRef}>
      {iframeRef.current && ReactDOM.createPortal(children, iframeRef.current.contentDocument.body)}
    </iframe>
  );
}

When Not to Use React Portal

While portals are powerful, they are not always necessary. Consider avoiding them when:

  • The component does not need to break out of its parent container.
  • CSS alone can handle layout issues, such as z-index adjustments.
  • Strict parent-child relationships are necessary for event handling.

React portals provide an elegant way to render components outside their natural DOM hierarchy without losing React’s reactivity. They solve layout and positioning challenges for modals, tooltips, pop-ups, and dropdowns while preserving event bubbling and React state management.

Learn React for Free
Start learning now
button icon
To advance beyond this tutorial and learn React by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH