UNPKG

1.94 kBJavaScriptView Raw
1import { useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
2import ReactDOM from 'react-dom';
3import canUseDom from "./Dom/canUseDom";
4var Portal = /*#__PURE__*/forwardRef(function (props, ref) {
5 var didUpdate = props.didUpdate,
6 getContainer = props.getContainer,
7 children = props.children;
8 var parentRef = useRef();
9 var containerRef = useRef();
10
11 // Ref return nothing, only for wrapper check exist
12 useImperativeHandle(ref, function () {
13 return {};
14 });
15
16 // Create container in client side with sync to avoid useEffect not get ref
17 var initRef = useRef(false);
18 if (!initRef.current && canUseDom()) {
19 containerRef.current = getContainer();
20 parentRef.current = containerRef.current.parentNode;
21 initRef.current = true;
22 }
23
24 // [Legacy] Used by `rc-trigger`
25 useEffect(function () {
26 didUpdate === null || didUpdate === void 0 || didUpdate(props);
27 });
28 useEffect(function () {
29 // Restore container to original place
30 // React 18 StrictMode will unmount first and mount back for effect test:
31 // https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors
32 if (containerRef.current.parentNode === null && parentRef.current !== null) {
33 parentRef.current.appendChild(containerRef.current);
34 }
35 return function () {
36 var _containerRef$current;
37 // [Legacy] This should not be handle by Portal but parent PortalWrapper instead.
38 // Since some component use `Portal` directly, we have to keep the logic here.
39 (_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 || (_containerRef$current = _containerRef$current.parentNode) === null || _containerRef$current === void 0 || _containerRef$current.removeChild(containerRef.current);
40 };
41 }, []);
42 return containerRef.current ? /*#__PURE__*/ReactDOM.createPortal(children, containerRef.current) : null;
43});
44export default Portal;
\No newline at end of file