How to use React portals for modals and overlays

· Category: React

Short answer

React portals let you render a child component into a different part of the DOM tree, such as a dedicated modal root element, while keeping the component in the original React tree.

Steps

  1. Create a container element in your HTML, such as <div id="modal-root"></div>.
  2. Import createPortal from react-dom.
  3. Return createPortal(children, domNode) from your component.

Example

import { createPortal } from 'react-dom';

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

Tips

  • Portals preserve event bubbling through the React tree, even though the DOM node is elsewhere.
  • Ensure the portal target exists in the DOM before rendering.
  • Combine portals with aria-modal and focus trapping for accessible modals.