Portals in React: Creating Powerful UI Overlays and Modal Dialogs

Olga Green
5 min readJul 31, 2023

--

React has revolutionized the way developers build user interfaces, providing a component-based architecture and a virtual DOM for efficient rendering. However, there are situations where components need to render outside of their usual position in the DOM hierarchy. This is where “portals” come into play. In this blog, we will explore the concept of portals in React, how they work, and the various use cases they enable. By the end of this article, you’ll have a thorough understanding of what are portals in React and how to leverage them effectively in your React applications.

What are Portals in React?

Portals are a powerful feature introduced in React 16 that allow components to render their content outside of the typical parent-child relationship in the DOM. With portals, developers can render a component’s content at a different DOM node, even outside the root DOM element of the application.

The primary motivation behind portals is to facilitate the creation of UI overlays, modal dialogs, tooltips, and any other scenarios where the content needs to break out of the parent component’s DOM boundaries while still maintaining the benefits of React’s component architecture.

Photo by Zan

How Portals Work?

The process of creating and using portals in React is straightforward. To render a component using a portal, you define a new DOM node as the target container, outside of the regular DOM hierarchy. Then, you use the ReactDOM.createPortal() method to render the component's content into that target container.

import React from 'react';
import ReactDOM from 'react-dom';
const PortalComponent = () => {
return ReactDOM.createPortal(
<div>
{/* Content to render outside the regular DOM hierarchy */}
</div>,
document.getElementById('portal-container') // Target container outside the root element
);
};

In the example above, the PortalComponent renders its content into the DOM node with the ID portal-container, which can be any DOM element outside the root element of the application.

Use Cases for Portals

Portals in React open up a myriad of possibilities for creating sophisticated user interfaces. Let’s explore some common use cases where portals prove to be invaluable:

a. Modals and Dialogs: Portals are perfect for rendering modals and dialogs that overlay the rest of the application. Modals can be used to display additional information, gather user input, or confirm actions, all while keeping the UI clean and uncluttered.

b. Tooltips and Popovers: Creating tooltips and popovers often involves rendering small content that appears when users hover over or interact with specific elements. Portals make it easy to position these elements precisely relative to their triggers.

c. Toast Messages: Toast messages, which provide notifications to users, can be rendered using portals to appear at the top or bottom of the screen without disturbing the application’s layout.

d. Context Menus: Portals enable context menus to appear at the cursor position, providing a user-friendly and intuitive interface.

e. Drag-and-Drop: Implementing drag-and-drop functionality often requires moving elements outside their original container, and portals facilitate this process seamlessly.

Limitations of Portals

While React portals offer great flexibility, there are some considerations and limitations to keep in mind:

a. Event Bubbling: Events emitted within a portal component do not bubble up the React component tree. This means that event handling requires special consideration when using portals.

b. DOM Order: Although portals allow rendering outside of the root element, the order of DOM nodes still matters for accessibility and CSS stacking contexts.

c. No Shadow DOM: Portals do not create Shadow DOM. This means that styles in the portal component can potentially affect the parent DOM and vice versa.

Best Practices for Using Portals

While portals offer great flexibility and open up new possibilities in React development, it’s essential to use them judiciously and follow best practices to ensure a smooth and maintainable codebase. Here are some best practices for using portals effectively:

  1. Choose Suitable Target Containers: When using portals, carefully select the target container outside the root element. The target container should be logically placed in the DOM and not disrupt the overall structure of the application. Avoid using containers that may interfere with critical elements or styling of the main application.
  2. Handle Events Appropriately: Events emitted within a portal component do not bubble up the React component tree. When handling events inside portal components, developers need to be mindful of event propagation and ensure that events are correctly captured and handled as intended. This may require using event listeners and passing down event handlers from the parent component.
  3. Properly Cleanup: Ensure that you handle cleanup when the portal component is unmounted. If a portal component is rendered conditionally and is removed from the DOM, any event listeners or resources associated with it should be properly cleaned up to avoid memory leaks or unexpected behavior.
  4. Avoid Overusing Portals: While React portal are a powerful tool, it’s essential not to overuse them. Reserve portals for situations where they offer clear advantages over traditional rendering. Overusing portals can make the application’s structure harder to maintain and lead to a less intuitive codebase.
  5. Maintain Accessibility: When using portals, pay attention to accessibility considerations. Make sure the content rendered through portals is accessible to all users, including those who rely on assistive technologies. Properly label and associate portal content with relevant elements to ensure a consistent and inclusive user experience.

Implementing a Modal with Portals

Let’s walk through an example of creating a simple modal using portals:

import React from 'react';
import ReactDOM from 'react-dom';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;

return ReactDOM.createPortal(
<div className="modal-overlay">
<div className="modal-content">
{children}
<button onClick={onClose}>Close</button>
</div>
</div>,
document.getElementById('modal-root')
);
};
export default Modal;

In this example, the Modal component uses portals to render its content into the DOM node with the ID modal-root, which is placed outside the root element of the application.

Conclusion

Portals in React provide a powerful and flexible way to render components outside of their usual DOM hierarchy. By leveraging portals, developers can create modal dialogs, tooltips, context menus, and more, without sacrificing the benefits of React’s component architecture.

Understanding how portals work and their various use cases empowers React developers to build sophisticated and user-friendly interfaces. By following best practices and considering the limitations, developers can harness the full potential of portals to enhance the user experience and create more interactive and engaging applications.

Portals offer an excellent solution for situations where traditional rendering may not suffice, making them an essential tool in a hire reactjs developer toolkit. By embracing portals, developers can take their React applications to the next level of interactivity and user experience, ensuring they stand out in today’s competitive web development landscape.

By partnering with CronJ, developers can tap into a wealth of expertise in React development and portals. CronJ’s dedication to staying up-to-date with the latest advancements and best practices in React ensures that their clients receive cutting-edge solutions that align with their business objectives.

References

  1. https://reactjs.net/
  2. https://medium.com/@greennolgaa/mastering-useeffect-in-react-js-a-comprehensive-guide-709a8024cb60
  3. useContext in Class Component
  4. React Middleware Example
  5. What is Diff Algorithm in React

--

--

Olga Green

Hello! I’m Olga Green. My design practice combines design thinking, user research and experience strategy.