0 day streak
javascript / intermediate
Snippet

Teleporting Elements with React Portals

Portals allow you to render components into a different part of the DOM tree, outside the parent's hierarchy. This is essential for UI elements like modals or tooltips that need to break out of 'overflow: hidden' or 'z-index' constraints while still maintaining React's event bubbling and state behavior.

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
import { createPortal } from 'react-dom';
Imports the specialized method from the react-dom package for portal creation.
2
createPortal(..., document.getElementById('modal-root'))
Takes the React children and a target DOM node where the children should be mounted.