This content originally appeared on Bits and Pieces - Medium and was authored by Amit Kumar
How React Portals work — explained with an example.
Welcome to the world of Portals in React! Are you ready to learn a new concept that will level up your React skills?
First of all, what are Portals? In simple terms, Portals allow you to render components outside of their parent component’s tree. This means that you can take a piece of your UI and place it anywhere on the page, regardless of its parent component. Portals are a powerful tool that can help you solve complex UI problems in creative ways.
React Portals are a handy way to render a component outside of its parent component in the DOM tree. If you’re a beginner React developer, you might be wondering what they are and how they work. In this article, we’ll go over a full working example of a React application using Portals and explain how they work in detail. Let’s get started!
Playing around with React Portals
Let’s say you’re reading a book and suddenly, you want to write down some notes about it. You reach for your trusty notebook and pen, but when you open it, you see that all the pages are full and there’s no space to write anything! What do you do?
This is where Portals come in to save the day! Just like how you can create a new notebook to keep your notes in, you can use Portals in React to keep your components separate from the rest of the page. This way, you can keep your components organized and make sure they don’t interfere with the rest of your UI.
Let’s see how Portals work in a real-life example. Consider a simple React application that displays a list of books. Now, let’s say we want to add a modal that displays more information about a selected book. But we want this modal to appear at bottom of body of the page, no matter where the user clicks on the page.
import React, { useState } from "react";
import { createPortal } from "react-dom";
const BooksList = () => {
const [selectedBook, setSelectedBook] = useState(null);
const books = [
{ id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
{ id: 2, title: "To Kill a Mockingbird", author: "Harper Lee" },
{ id: 3, title: "Pride and Prejudice", author: "Jane Austen" }
];
const handleBookSelect = (book) => {
setSelectedBook(book);
};
return (
<div>
{selectedBook && (
<BookInfoModal
book={selectedBook}
onClose={() => setSelectedBook(null)}
/>
)}
<h2>Books List</h2>
<ul>
{books.map((book) => (
<li key={book.id} onClick={() => handleBookSelect(book)}>
{book.title} by {book.author}
</li>
))}
</ul>
</div>
);
};
const BookInfoModal = ({ book, onClose }) => {
return createPortal(
<div
style={{
backgroundColor: "rgba(0,0,0,0.5)",
padding: 10
}}
>
<div
style={{
backgroundColor: "white",
padding: 20
}}
>
<h2>{book.title}</h2>
<p>by {book.author}</p>
<button onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
};
export default BooksList;
In this example, we use the createPortal function from the react-dom library to create a Portal. We pass in two arguments: the component to be rendered (in this case, a div with some styling) and the target DOM node where we want to render it (in this case, document.body).
Similarly, we can also create portal like below to another target DOM node:
function BookModal({ bookName }) {
return ReactDOM.createPortal(
<div>
<h1> More Information About {bookName} </h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id
facilisis nulla. Nullam posuere, magna vitae pellentesque tempor,
ipsum justo tincidunt nulla, a consectetur nibh dolor vel ipsum.
</p>
</div>,
document.getElementById('modal-root')
);
}
We also use the useState hook to keep track of whether the modal should be displayed or not. When the user clicks the on "book", the selectedBook state is updated and the modal appears or disappears.
Let’s dive into the internal workings of Portals in React. React Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This means that the children will be rendered outside of its parent component in the DOM tree, but still within the same React component tree.
When you render a component with createPortal, React creates a new React tree that is completely separate from the parent component. This allows you to render the component anywhere on the page, independent of its parent component.
Portals provide a way to render a component outside of its parent component tree, yet still maintain its connection to the React tree. This means that even though a component is rendered outside of its parent, it will still receive props, maintain its state, and respond to events as if it were still within its parent component.
When using Portals, you need to specify a DOM node where the children will be rendered. In the previous example, we used a DOM node with the id of “modal-root”. This allows us to render the Modal component outside of the main component tree and into the “modal-root” node.
It is important to remember that UI added using portal will always be appended inside the target DOM node.
Also note that while Portals are great for creating modals and such outside the DOM tree, using toos like Bit, you can make them even more reusable by using your Portals in any other project you want with a single npm install.
When should you use portals?
Portals in React work by creating a new root DOM node in the HTML document and rendering the component into that node. The portal component acts as a bridge between the parent component and the new DOM node, allowing you to pass data and events between them.
Portals provide a number of benefits when it comes to working with React components. Here are a few of the most common use cases:
- Modals and dialogs: Portals are great for creating modals and dialogs that need to be rendered on top of the main content.
- Tooltips and popovers: You can also use Portals to create tooltips and popovers that need to be positioned relative to a specific component.
- Overlaying content: Portals can also be used to render content that needs to be overlaid on top of the main content, such as a loading spinner or a notification message.
Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.
Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.
Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:
→ Micro-Frontends
→ Design System
→ Code-Sharing and reuse
→ Monorepo
Learn more
- How We Build Micro Frontends
- How we Build a Component Design System
- How to reuse React components across your projects
- 5 Ways to Build a React Monorepo
- How to Create a Composable React App with Bit
Discover the Magic of Portals: A Beginner’s Guide to React’s Most Powerful Tool was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Amit Kumar

Amit Kumar | Sciencx (2023-02-07T11:44:25+00:00) Discover the Magic of Portals: A Beginner’s Guide to React’s Most Powerful Tool. Retrieved from https://www.scien.cx/2023/02/07/discover-the-magic-of-portals-a-beginners-guide-to-reacts-most-powerful-tool/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.