javascript / intermediate
Snippet
Rendering with React Portals
Portals allow you to render children into a DOM node that exists outside the hierarchy of the parent component. This is commonly used for UI elements like modals, tooltips, and dropdowns to avoid CSS issues with overflow: hidden or z-index.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { createPortal } from 'react-dom';const Modal = ({ isOpen, children, onClose }) => {if (!isOpen) return null;return createPortal(<div className="modal-overlay"><div className="modal-content">{children}<button onClick={onClose}>Close</button></div></div>,document.body);};
react
Breakdown
1
createPortal(children, document.body)
The first argument is the content to render; the second is the target DOM node outside the current tree.
2
document.body
A common target for portals, ensuring the element is at the top level of the DOM structure.