import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import useSSR from 'use-ssr';
import { isHTMLElement, isUndefined } from '../../common/utils';
export var Portal = function Portal(_ref) {
  var children = _ref.children,
    attachTo = _ref.attachTo;
  var _useSSR = useSSR(),
    isBrowser = _useSSR.isBrowser,
    isServer = _useSSR.isServer;
  var portal = useRef(isBrowser && document.createElement('div'));
  useEffect(function () {
    var elToMountTo = isUndefined(attachTo) ? document.body : attachTo;
    var portalNode = portal.current;
    if (isServer || !isHTMLElement(elToMountTo) || !isHTMLElement(portalNode)) {
      return;
    }
    elToMountTo.appendChild(portalNode);
    return function cleanup() {
      elToMountTo.removeChild(portalNode);
    };
  }, [attachTo, isServer]);
  return isHTMLElement(portal.current) ? createPortal(children, portal.current) : null;
};