Skip to content

Commit 278b545

Browse files
authored
fix: prevent from creating multi portals again (#294)
* Revert "Revert "fix: prevent from creating multi portals (#292)" (#293)" This reverts commit fd694b6. * chore: patch
1 parent c95d6fd commit 278b545

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

src/index.tsx

Lines changed: 25 additions & 12 deletions
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;
@@ -587,18 +590,28 @@ export function generateTrigger(
587590
};
588591

589592
getContainer = () => {
590-
const { getDocument } = this.props;
591-
const popupContainer = getDocument(this.getRootDomNode()).createElement(
592-
'div',
593-
);
594-
// Make sure default popup container will never cause scrollbar appearing
595-
// https://github.com/react-component/trigger/issues/41
596-
popupContainer.style.position = 'absolute';
597-
popupContainer.style.top = '0';
598-
popupContainer.style.left = '0';
599-
popupContainer.style.width = '100%';
600-
this.attachParent(popupContainer);
601-
return popupContainer;
593+
if (!this.portalContainer) {
594+
// In React.StrictMode component will call render multiple time in first mount.
595+
// When you want to refactor with FC, useRef will also init multiple time and
596+
// point to different useRef instance which will create multiple element
597+
// (This multiple render will not trigger effect so you can not clean up this
598+
// in effect). But this is safe with class component since it always point to same class instance.
599+
const { getDocument } = this.props;
600+
const popupContainer = getDocument(this.getRootDomNode()).createElement(
601+
'div',
602+
);
603+
// Make sure default popup container will never cause scrollbar appearing
604+
// https://github.com/react-component/trigger/issues/41
605+
popupContainer.style.position = 'absolute';
606+
popupContainer.style.top = '0';
607+
popupContainer.style.left = '0';
608+
popupContainer.style.width = '100%';
609+
this.attachParent(popupContainer);
610+
611+
this.portalContainer = popupContainer;
612+
}
613+
614+
return this.portalContainer;
602615
};
603616

604617
/**

0 commit comments

Comments
 (0)