Skip to content

Commit 03d0ad0

Browse files
authored
fix: prevent from creating multi portals (#292)
* fix: prevent from creating multi portals * chore: add comments * chore: add comments
1 parent ac05814 commit 03d0ad0

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/index.tsx

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,9 @@ export function generateTrigger(
156156

157157
triggerRef = React.createRef<React.ReactInstance>();
158158

159+
// ensure `getContainer` will be called only once
160+
portalContainer?: HTMLElement;
161+
159162
attachId?: number;
160163

161164
clickOutsideHandler: CommonEventHandler;
@@ -858,10 +861,18 @@ export function generateTrigger(
858861
let portal: React.ReactElement;
859862
// prevent unmounting after it's rendered
860863
if (popupVisible || this.popupRef.current || forceRender) {
864+
if (!this.portalContainer) {
865+
// In React.StrictMode component will call render multiple time in first mount.
866+
// When you want to refactor with FC, useRef will also init multiple time and
867+
// point to different useRef instance which will create multiple element
868+
// (This multiple render will not trigger effect so you can not clean up this
869+
// in effect). But this is safe with class component since it always point to same class instance.
870+
this.portalContainer = this.getContainer();
871+
}
861872
portal = (
862873
<PortalComponent
863874
key="portal"
864-
getContainer={this.getContainer}
875+
getContainer={() => this.portalContainer}
865876
didUpdate={this.handlePortalUpdate}
866877
>
867878
{this.getComponent()}

0 commit comments

Comments
 (0)