import React from 'react';
import ReactDOM from 'react-dom';
import invariant from 'tiny-invariant';

interface DynamicPortalProps {
  children: React.ReactNode;
}

const DynamicPortal: React.FC<DynamicPortalProps> = (props) => {
  const { children } = props;
  const [el] = React.useState(() => document.createElement('div'));
  React.useEffect(() => {
    const body = document.querySelector('body');
    invariant(body, 'The body element is not available. Please ensure this code runs in a browser context.');
    if (el.parentNode == null) {
      body.appendChild(el);
    }
    return () => {
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      }
    };
  }, [el]);
  return ReactDOM.createPortal(children, el);
};
export default DynamicPortal;
