Lesson 38 +10 XP

React Portals

React Portals

Sometimes a component needs to render visually outside its parent DOM hierarchy—for example, modal dialogs, tooltips, popovers, or floating notification banners that need to break out of overflow: hidden or z-index CSS stacking contexts.

What is a React Portal?

Portals provide a way to render a child element into a different DOM node that exists outside the parent component's DOM element tree.

Using createPortal

Import createPortal from react-dom. It accepts two arguments:

  1. The JSX element you want to render.
  2. The target HTML DOM element container where it should be inserted.
import { createPortal } from 'react-dom';

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

  // Render modal content directly into <div id="modal-root"></div> in index.html
  return createPortal(
    <div className="modal-overlay">
      <div className="modal-content">
        <button className="close-btn" onClick={onClose}>×</button>
        {children}
      </div>
    </div>,
    document.getElementById('modal-root') // Target DOM container node
  );
}

Event Bubbling Through Portals

Even though a portal element renders into a completely different location in the HTML DOM tree, React event bubbling behaves as if the component were still inside the React tree.

An event fired from inside a portal component will bubble up to its parent component in the React component tree!

Summary & TL;DR

  • createPortal(children, domNode) renders React elements into a target DOM node outside the parent hierarchy.
  • Essential for Modals, Tooltips, Context Menus, and Overlay dialogs.
  • Prevents CSS overflow: hidden and z-index clipping issues.
  • React event bubbling continues to work through portals according to the React component hierarchy.