0PricingLogin
React Academy · Lesson

Building a Modal Component with Portals

Create a reusable modal that renders into document.body via createPortal.

Welcome

In this lesson you will build a reusable Modal component that uses React.createPortal to render into document.body, with backdrop click and Escape key close support.

Modal Component Skeleton

Start with the basic structure: a Modal component that accepts `isOpen`, `onClose`, and `children` props. When `isOpen` is false, render nothing.
function Modal({ isOpen, onClose, children }) {
  if (!isOpen) return null;
  return createPortal(
    <div className="backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        {children}
      </div>
    </div>,
    document.body
  );
}

All lessons in this course

  1. What Are React Portals?
  2. Building a Modal Component with Portals
  3. Handling Focus & Keyboard Traps in Modals
  4. Tooltips & Dropdown Menus with Portals
← Back to React Academy