/
Portal.tsx
47 lines (37 loc) · 1.34 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
import * 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 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();
initRef.current = true;
}
// [Legacy] Used by `rc-trigger`
useEffect(() => {
didUpdate?.(props);
});
useEffect(() => {
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;