-
Notifications
You must be signed in to change notification settings - Fork 178
/
Portal.tsx
58 lines (48 loc) · 1.81 KB
/
Portal.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import type * as React from 'react';
import { useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
import ReactDOM from 'react-dom';
import canUseDom from './Dom/canUseDom';
export type PortalRef = {};
export interface PortalProps {
didUpdate?: (prevProps: PortalProps) => void;
getContainer: () => HTMLElement;
children?: React.ReactNode;
}
const Portal = forwardRef<PortalRef, PortalProps>((props, ref) => {
const { didUpdate, getContainer, children } = props;
const parentRef = useRef<ParentNode>();
const containerRef = useRef<HTMLElement>();
// Ref return nothing, only for wrapper check exist
useImperativeHandle(ref, () => ({}));
// Create container in client side with sync to avoid useEffect not get ref
const initRef = useRef(false);
if (!initRef.current && canUseDom()) {
containerRef.current = getContainer();
parentRef.current = containerRef.current.parentNode;
initRef.current = true;
}
// [Legacy] Used by `rc-trigger`
useEffect(() => {
didUpdate?.(props);
});
useEffect(() => {
// Restore container to original place
// React 18 StrictMode will unmount first and mount back for effect test:
// https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors
if (
containerRef.current.parentNode === null &&
parentRef.current !== null
) {
parentRef.current.appendChild(containerRef.current);
}
return () => {
// [Legacy] This should not be handle by Portal but parent PortalWrapper instead.
// Since some component use `Portal` directly, we have to keep the logic here.
containerRef.current?.parentNode?.removeChild(containerRef.current);
};
}, []);
return containerRef.current
? ReactDOM.createPortal(children, containerRef.current)
: null;
});
export default Portal;