This small blog post is about React Portals - when and where to use them and IF you need to use them.
Introduction
As a frontend developer I am working with React for almost 5 years and I never had a need to use Portals. But once I was watching a learning video and this topic came up. I decided to learn a bit more about Portals and share the knowledge about this topic.
What is Portal?
Portal is a mechanism or pattern, which provides a way to render content outside the current DOM hierarchy.
Usually React renders child components inside the parent components DOM, but sometimes you need to render those children outside the parent's DOM - for example on the higher level of app DOM:
<body>
<div id="modal">{child}</div> <-- for example here
<div id="content">{~~child~~}</div> <-- instead of here
</body>
There are specific use cases where to use Portals and we will look at them below in this post.
Definition
Portal is created by a function call from "react-dom" library createPortal()
.
It accepts:
-
child
: the React element you want to render. -
container
: the actual DOM node (outside your app’s root) where it should be inserted.
It returns a React element that React knows how to mount into a different DOM node. It kinda tells React: “Render this child over here”:
ReactDOM.createPortal(child, container)
Here is an example of how it works under the hood:
const modal = document.getElementById('modal');
const portalElement = ReactDOM.createPortal(
<div>My Modal</div>,
modal
);
This means: you’re telling React to render <div>My Modal</div>
.
But instead of placing it where the component is written, React inserts it into modal
. It’s part of the virtual DOM tree, but lives outside the regular DOM tree.
When to use Portals
There are some child components for which its recommended to use Portals IF you write them from scratch:
- Modals / Dialogs
- Tooltips
- Popovers
- Dropdowns
- Overlays
For these components there are some benefits when using Portals:
- it helps to escape parent styles ( like
overflow: hidden
style) - it helps to manage their focus correctly - useful for accessibility
- it still keeps React context - works with state, hooks etc.
Use Portals WHEN:
- you are building your own custom modal or dialog
- you are working on design systems or low-level UI frameworks
- you need manual DOM isolation for layout or z-index issue
Most of existing UI libraries (like MaterailUI) are using Portals already under the hood - so we benefit from them without writing one ourselves :)
Top comments (0)