What is a React Portal and why would you use one?
Short answer
A Portal lets you render a component's content into a different part of the actual page structure, outside of its normal parent element, while it still behaves like a normal part of your React component tree.
Advertisement
AModel answer
A Portal lets you render a component's content into a different part of the actual page structure, outside of its normal parent element, while it still behaves like a normal part of your React component tree. This is commonly used for things like modals and tooltips, which need to visually sit on top of everything else on the page.
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal">{children}</div>,
document.getElementById('modal-root')
);
}Real-world example
A shopping site renders its checkout confirmation modal directly into a special modal-root element at the very end of the page's HTML, avoiding layout and overflow issues that could happen if it stayed nested deep inside the page's normal structure.
Likely follow-ups
- Does a Portal still receive events the same way as a normally placed component?
- What HTML element do you usually create in advance for a Portal to render into?
Related topics