React Portals

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This is extremely useful for UI elements like modals, tooltips, and popups.

Why use Portals?

Normally, when you render an element in React, it's mounted into the DOM as a child of the nearest parent node. However, sometimes you want the component to physically exist somewhere else in the DOM (like at the end of the body) to avoid overflow: hidden or z-index issues from parent containers.

Syntax

JavaScript

import { createPortal } from 'react-dom';

function MyPortalComponent({ children }) {
  const domNode = document.getElementById('portal-root');
  return createPortal(children, domNode);
}          

Example: Building a Modal

Here is how you can use a portal to create a Modal that renders into a separate div in your index.html.

JavaScript

import React from 'react';
import { createPortal } from 'react-dom';

function Modal({ isOpen, onClose, children }) {
  if (!isOpen) return null;

  return createPortal(
    <div className="modal-overlay">
      <div className="modal-content">
        {children}
        <button onClick={onClose}>Close</button>
      </div>
    </div>,
    document.body // Rendering directly into body
  );
}

export default Modal;          

Event Bubbling

Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the React tree, even if those elements are not ancestors in the DOM tree.

Note: Always ensure the DOM node you are targeting for the portal exists before the component mounts.