Portal.js 1.9 KB

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