Member-only story
Unlocking the Secrets of React Portals: A Fun Guide with Examples
React portals are like secret passageways in your code that allow you to transport a component to a different location in the DOM, without its parent even knowing about it. Imagine you have a parent component that renders a modal, but for some reason, you want the modal to appear in a different place on the page. With React portals, you can make that happen!
2 min readJan 22, 2023
To create a portal, you first need to create a DOM node that will act as the portal’s destination. This can be done by adding an empty div
element to your HTML, and giving it an id, like so:
<div id="modal-root"></div>
Next, you’ll need to import the createPortal
method from the react-dom
library, and use it to render your component in the DOM node you just created.
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(children, document.getElementById('modal-root'));
}
And that’s it! Now, when you render your modal component, it will appear in the modal-root
DOM node, instead of inside its parent…