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
- What Are React Portals?
- Building a Modal Component with Portals
- Handling Focus & Keyboard Traps in Modals
- Tooltips & Dropdown Menus with Portals