Skip to content

Commit 92a61aa

Browse files
authored
docs(blog): add react portal post (#5102)
1 parent d36c870 commit 92a61aa

File tree

1 file changed

+174
-0
lines changed

1 file changed

+174
-0
lines changed
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
---
2+
title: A complete guide to the React createPortal API
3+
description: We'll explore the React createPortal API, its advantages, disadvantages, and possible use cases.
4+
slug: react-createportal
5+
authors: joseph_mawa
6+
tags: [react]
7+
image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-10-12-react-createportal/social.png
8+
hide_table_of_contents: false
9+
---
10+
11+
12+
## Introduction
13+
14+
The `createPortal` API is part of the React DOM. You can use it to flexibly render the children of a React component in another location in the DOM. Though you can render a portal in another location, it still behaves like any other React child component.
15+
16+
This behavior of the `createPortal` API makes it easy to create UIs such as tooltips, toasts, modals, and popups. This article will take a deep dive into the `createPortal` API. We will explore its advantages, disadvantages, and possible use cases.
17+
18+
## Complete guide to the `createPortal` API
19+
20+
As explained above, the `createPortal` API is part of the React DOM API. Therefore, before using it, you need to import it from `react-dom` like so:
21+
22+
```tsx
23+
import { createPortal } from "react-dom";
24+
```
25+
26+
Ordinarily, a React component and its children have a parent-child relationship, and all the children are nested within their parent after rendering.
27+
28+
However, with the `createPortal` API, a React component can render all or some of its children in another location in the DOM rather than the parent. The code below shows its function signature.
29+
30+
```tsx
31+
createPortal(children, domNode, key?)
32+
```
33+
34+
The `children` parameter of the `createPortal` function must be a React component, JSX, React Fragment, string, number, or an array of these.
35+
36+
The `domNode` parameter is the DOM Node in which you want to render the `children`. You can use the `document.getElementById` method or any of the element-lookup methods of the `document` object.
37+
38+
The last parameter is an optional key. It is a unique string or number that will be used as the portal's key.
39+
40+
The `createPortal` function returns a React Node. Therefore, you can return it from a React component or render it inside another component's JSX, as in the example below.
41+
42+
```tsx
43+
import { createPortal } from "react-dom";
44+
45+
export function PortalDemo() {
46+
return (
47+
<div>
48+
<p>This child is placed in the parent div.</p>
49+
{createPortal(
50+
<p>This child is placed in the document body.</p>,
51+
document.body
52+
)}
53+
</div>
54+
);
55+
}
56+
```
57+
58+
When you render a component using the `createPortal` API, only the rendering of the component in the DOM changes. Everything else remains the same. The events generated from the portal will bubble in the React Node hierarchy not in the DOM hierarchy.
59+
60+
Though a portal is rendered in a different location in the DOM, it is still a child of the parent React Component that renders it. It re-renders whenever the props or context passed to it changes, and its parent re-renders.
61+
62+
63+
---
64+
65+
<BannerRandom />
66+
67+
---
68+
69+
## Pros of the `createPortal` API
70+
71+
There are several benefits of the `createPortal` API. Below are some of these benefits.
72+
73+
### Rendering an element in another location in the DOM
74+
75+
The biggest benefit of the `createPortal` API is that it gives you the flexibility to render an element outside its parent in another DOM element therefore breaking out of the usual parent-child relationship between components.
76+
77+
This helps you to easily build certain UIs, such as tooltips and modals which might otherwise be difficult without portals.
78+
79+
### Integrating third-party packages into your project
80+
81+
More often than not, you may want to integrate third-party packages that do not use React in your React application. The `createPortal` API makes it easy because you can use it to render a React component anywhere in the DOM.
82+
83+
## Cons of the `createPortal` API
84+
85+
As hinted above, the `createPortal` API comes in handy when you're looking to render a component in a different location in the DOM. It is without doubt a very useful feature of the `react-dom` package and has very many useful applications.
86+
87+
However, the `createPortal` API is not without drawbacks. Let's explore its disadvantages in this section.
88+
89+
### CSS Inherited properties
90+
91+
Though a portal is still a child of its parent React component, it doesn't inherit CSS properties applied to its parent because it's rendered in a different location in the DOM. This may result in hard-to-find bugs, especially when dealing with complex portals.
92+
93+
In the example below, I'm applying `color: red` to the parent `div`. Ordinarily, the nested `p` elements inherit the `color` property from their parent. However, the `p` element rendered using `createPortal` won't because it is rendered in a different location in the DOM.
94+
95+
```tsx
96+
import { createPortal } from "react-dom";
97+
98+
function PortalDemo() {
99+
return (
100+
<div style={{ color: "red" }}>
101+
<p>This will be red.</p>
102+
103+
{createPortal(
104+
<p>This won't be red.</p>,
105+
document.getElementById("portal")
106+
)}
107+
</div>
108+
);
109+
}
110+
```
111+
112+
Such behavior may result in bugs that may be difficult to trace, especially when dealing with complex applications.
113+
114+
### Complex portals are difficult to maintain
115+
116+
Portals may become difficult to maintain if you're dealing with complex interdependent portals. Similarly, it is difficult to reason about the components and the application because of the mismatch between the location of the portal in the DOM and where it is rendered in the React component.
117+
118+
### Accessibility issues
119+
120+
As we will discuss in the next subsection, the most common use-cases of the `createPortal` API are for creating toasts, modals, and popups. You will need to go above and beyond to make them accessible.
121+
122+
### Mismatch between location in the DOM and event bubbling
123+
124+
When you render an element in the DOM using `createPortal`, the events bubble up the React tree, not the DOM tree. The mismatch between the location of a portal in the DOM and event bubbling may make debugging a little more difficult in complex applications.
125+
126+
## Use cases of the `createPortal` API
127+
128+
As hinted above, the most common use-case of the `createPortal` API is for building UIs such as modals, tooltips, popups, and toasts.
129+
130+
The example below shows how to use portals to implement a basic modal in React. You can also implement tooltips, popups, and toasts pretty much similarly.
131+
132+
The example below is a basic illustration of the `createPortal` API without styling.
133+
134+
```tsx
135+
import { useState } from "react";
136+
import { createPortal } from "react-dom";
137+
138+
function Modal({ onClose }) {
139+
return (
140+
<div className="modal">
141+
<p>This is a modal.</p>
142+
<button onClick={onClose}>Close</button>
143+
</div>
144+
);
145+
}
146+
147+
function App() {
148+
const [showModal, setShowModal] = useState(false);
149+
return (
150+
<div>
151+
<button onClick={() => setShowModal(true)}>Open modal.</button>
152+
{showModal &&
153+
createPortal(
154+
<Modal onClose={() => setShowModal(false)} />,
155+
document.body
156+
)}
157+
</div>
158+
);
159+
}
160+
161+
export default App;
162+
```
163+
164+
Furthermore, it is also possible to use the `createPortal` API to integrate React in a static page or a non-react application because it enables rendering React components anywhere in the DOM.
165+
166+
## Conclusion
167+
168+
As explained above, the `createPortal` API is part of the React DOM API. It is for rendering the children of a React component in another location in the DOM.
169+
170+
Though a portal is rendered in another location, it behaves like any React child component. It re-renders when its state, props, or context changes and when the parent component re-renders.
171+
172+
The `createPortal` function takes the `children`, `domNode`, and an optional `key` as arguments and returns a React Node, which you can render in another React component or JSX.
173+
174+
You can use the `createPortal` API to create toasts, modals, tooltips, and popups such as cookie permissions popups. However, make sure any portal you create is accessible.

0 commit comments

Comments
 (0)