javascript / intermediate
Snippet
Rendering Outside the DOM Hierarchy with Portals
Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This is critical for UI elements like modals, tooltips, or floating menus that should not be clipped by 'overflow: hidden' or affected by 'z-index' in the parent.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { createPortal } from 'react-dom';function Modal({ children }) {return createPortal(<div className="modal-overlay">{children}</div>,document.getElementById('modal-root'));}
react
Breakdown
1
createPortal(children, document.getElementById('modal-root'))
Takes the React children and a target DOM element to render them into.