Portals for Modals and Tooltips
Use ReactDOM.createPortal to render children into a different DOM node, enabling modals and tooltips that escape overflow:hidden containers.
The Container Escape Problem
Modals and tooltips need to render at the top of the DOM, escaping overflow:hidden, z-index stacking, and transform-rooted contexts of their parent. Solution: portals.
createPortal API
createPortal(children, container) renders children into container (any DOM node) while keeping them logically children of the React component for events and context.
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="modal-backdrop" onClick={onClose}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
{children}
</div>
</div>,
document.body
);
}All lessons in this course
- Compound Components with Context
- Render Props and HOC Patterns
- Portals for Modals and Tooltips
- Error Boundaries