Intro
React Dom library exposed many APIs, and createPortal is one of them. With this, you can mount a component in another part of the dom tree. It is widely used to create UIs like tooltips, modals, and popups. We will look into its benefits, drawbacks, and potential applications.
How to use createPortal
:
As mentioned above createPortal is part of react-dom API. Thus, we must import it from react-dom like this before utilizing it.
import { createPortal } from "react-dom";
In the usual case, React components and their child components maintain a hierarchical parent-child relationship, where all the child components are rendered within their parent component.
Nonetheless, by utilizing the createPortal API, a React component gains the capability to render some or all of its child components at a different location in the DOM instead of within its immediate parent component. The code below displays the function signature for this functionality.
createPortal(children, domNode, key);
The createPortal
function requires a text or integer, or JSX or React Fragment, or an array of these as its children parameter.
The DOM Node in which you wish to render the children is indicated by the domNode option. You can use any of the document object's element-lookup methods or document.getElementById
.
An optional key is the final parameter. It is a distinct character or number that serves as the key for the portal.
A React Node is the result of the createPortal
function. Consequently, as demonstrated in the example below, you can render it inside the JSX of another component or return it from a React component.
import { createPortal } from "react-dom";
export function MyComponent() {
return (
<div style={{ border: "2px solid black" }}>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
document.body,
)}
</div>
);
}
When you use the createPortal
API to render a component, the only thing that changes is where the component is displayed in the DOM. Everything else remains unaffected. Any events generated within the portal continue to follow the React component hierarchy rather than the DOM hierarchy.
Despite the portal being rendered in a different DOM location, it maintains its status as a child of the parent React Component responsible for rendering it. This means it will re-render whenever there are changes to its props or context, as well as when its parent component undergoes a re-render.
Advantages of the createPortal
API:
The createPortal
API offers a range of benefits, some of which are outlined below.
- Rendering Elements in a Different DOM Location The primary advantage of the createPortal API is its ability to render an element outside its parent component, breaking away from the typical parent-child relationship that components maintain. This feature is particularly valuable when designing user interfaces that require elements to be displayed in unconventional locations, such as tooltips and modals.
- Integrating External Packages into Your Project In many cases, you may need to incorporate third-party packages that don't use React into your React application. The createPortal API simplifies this process, as it enables you to render a React component anywhere in the DOM, making it seamless to combine React-based components with non-React libraries and packages.
Disadvantages of the createPortal
API:
While the createPortal API provides significant advantages, it also has some drawbacks to consider. Here, we explore the limitations of this feature:
- Maintenance Challenges with Complex Portals: Complex portals, especially those with inter-dependencies, can become challenging to maintain. The disparity between the portal's location in the DOM and its rendering within the React component can make it difficult to reason about the components and the application's behavior. This can lead to maintenance issues, particularly in larger and more intricate applications.
- Accessibility Concerns: CreatePortal is often used for creating toasts, modals, and popups. These user interface elements require careful attention to accessibility to ensure they can be used by all individuals, including those with disabilities. Making portals accessible may require additional effort and consideration to comply with accessibility standards and guidelines.
- Mismatch in Event Bubbling: When an element is rendered in the DOM using createPortal, events bubble up the React component tree, rather than following the standard DOM tree event bubbling. This mismatch between the location of a portal in the DOM and the event bubbling can add complexity to debugging, especially in intricate applications. Understanding where events originate and how they propagate may be less intuitive when working with portals.
Use Cases of the createPortal
API:
As previously mentioned, the createPortal API is commonly employed for building user interfaces such as modals, tooltips, popups, and toasts. These are some of the primary scenarios where createPortal is highly beneficial. The example below demonstrates how to utilize portals to create a basic modal in a React application, but the same approach can be employed for implementing tooltips, popups, and toasts with slight variations.
The following example provides a basic illustration of using the createPortal
API without styling:
import { useState } from "react";
import { createPortal } from "react-dom";
function Tooltip({ text, onClose }) {
return (
<div className="tooltip">
<p>{text}</p>
<button onClick={onClose}>Close</button>
</div>
);
}
function App() {
const [showTooltip, setShowTooltip] = useState(false);
const tooltipText = "This is a tooltip.";
return (
<div>
<button
onMouseEnter={() => setShowTooltip(true)}
onMouseLeave={() => setShowTooltip(false)}
>
Hover for Tooltip
</button>
{showTooltip &&
createPortal(
<Tooltip text={tooltipText} onClose={() => setShowTooltip(false)} />,
document.body,
)}
</div>
);
}
export default App;
Moreover, the createPortal
API allows you to integrate React components into static web pages or non-React applications by enabling the rendering of React components in any location within the DOM.
Conclusion
In conclusion, the createPortal API, which is part of the React DOM API, serves the purpose of rendering the children of a React component in a different DOM location. Despite being rendered in an alternative location, a portal behaves like any other React child component, responding to changes in state, props, or context, and re-rendering when the parent component re-renders.
The createPortal function accepts children, a DOM node, and an optional key as arguments, returning a React Node that can be embedded in another React component or JSX. This versatility makes it a valuable tool for creating various UI elements, such as toasts, modals, tooltips, and popups, including components like cookie permission popups. It is important, however, to ensure that any portal you create is designed to be accessible to all users.