Read Time:2 Minute, 3 Second

In this article, we’ll dive into the concept of portals in React and see how they can be used to enhance your UI components.

Portals in React are a powerful tool for rendering components outside of their parent component’s DOM tree. They provide a way to detach a component from its parent and attach it to a different DOM node, rather than being inside its parent component. This allowing for greater flexibility and improved UI design. This can be useful in certain cases where you want to render a component that is logically a child of a certain component, but you need it to be physically detached from its parent component in the DOM tree.

With portals, you can create modals, tooltips, or other UI elements that need to be displayed on top of other components, regardless of their parent-child relationship. Portals are created using the ReactDOM.createPortal method and can be used to bring your components to life in new and creative ways.

Let’s say, you might have a modal component that you want to render outside of your main app component, so that it appears on top of other components regardless of the parent-child hierarchy. Portals provide a way to do this by creating a new root in the DOM and attaching your component to it. You provide the component you want to render and the DOM node where you want to render it.

For example:

function Modal({ children }) { return ReactDOM.createPortal(children, document.getElementById("modal-root"));
Enter fullscreen mode Exit fullscreen mode

Image description

In above example, we have a Modal component that renders its children using a portal. The document.getElementById('modal-root') is a DOM node that we’ve created elsewhere in our HTML file (index.html), where we want to render our modal component.

This way, we can render the modal component outside of the main app component and have it appear on top of other components.

DOM node that we’ve created in our HTML

<div id="modal-root"></div>
Enter fullscreen mode Exit fullscreen mode

Image description

Rendered HTML

The Modal component will be rendered into the modal-root element, which you would need to define in your HTML:

Image description


Please consider following and supporting us by subscribing to our channel. Your support is greatly appreciated and will help us continue creating content for you to enjoy. Thank you in advance for your support!