React Portals

React Portals

Portals provide an elegant, first-class way to seamlessly render children into a completely separate DOM node that exists fully outside the DOM hierarchy of the parent component. This is especially vital and heavily utilized for overlapping UI elements like modals, tooltips, and hover cards.

Creating a Portal

You use the ReactDOM.createPortal(child, container) function to establish a portal correctly.

import { createPortal } from 'react-dom';

function Modal({ children }) { return createPortal(children, document.getElementById('modal-root')); }