React Portals
Rendering outside the DOM tree, modals, tooltips, and event bubbling.
Overview
Portals let you render children into a different part of the DOM while keeping React events.
Key Concepts
- createPortal ā Renders children into a different DOM node
- Event Bubbling ā Events still propagate through React tree
- Use Cases ā Modals, tooltips, dropdowns, notifications
- CSS Isolation ā Style portal content independently
- SSR Considerations ā Portals require client-side rendering
Code Examples
import { createPortal } from 'react-dom';
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>Ć</button>
{children}
</div>
</div>,
document.getElementById('modal-root')
);
}
function App() {
const [isModalOpen, setIsModalOpen] = useState(false);
return (
<div>
<button onClick={() => setIsModalOpen(true)}>Open Modal</button>
<Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
<h2>Modal Content</h2>
<p>This is rendered outside the main DOM tree.</p>
</Modal>
</div>
);
}
Practice
Build a modal system with keyboard navigation and focus trapping.