// adapted from https://github.com/tajo/react-portal/blob/55ed77ab823b03d1d4c45b950ba26ea5d687e85c/src/LegacyPortal.js

import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";

type Props = {
  children: any;
};

function Portal(props: Props) {
  let defaultNodeRef = useRef<HTMLDivElement>(document.createElement("div"));
  useEffect(() => {
    document.body.appendChild(defaultNodeRef.current);
    let children = props.children;
    if (typeof children.type === "function") {
      children = React.cloneElement(children);
    }

    ReactDOM.render(children, defaultNodeRef.current);
    return () => {
      ReactDOM.unmountComponentAtNode(defaultNodeRef.current);
      if (defaultNodeRef.current) {
        document.body.removeChild(defaultNodeRef.current);
      }
    };
  });

  return null;
}

export default Portal;
