Portal.js 2.2 KB

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