import { ReactNode, useState, useEffect } from 'react';
import { createPortal } from 'react-dom';

export interface PortalProps {
    /** Content to render in the portal */
    children: ReactNode;

    /** Container to render the content */
    container?: HTMLElement | null;
}

export const Portal = (props: PortalProps): JSX.Element => {
    const { children, container } = props;

    // save where it is being mounted
    const [mounted, setMounted] = useState<boolean>(false);
    const [mountNode, setMountNode] = useState<HTMLElement | null>(null);

    // set the mount node based on the container
    useEffect(() => {
        // set that it has been mounted
        setMounted(true);

        // set the mount node
        setMountNode(container ? container : null);
    }, [container]);

    // don't render till it is mounted
    if (!mounted) {
        return <></>;
    }

    return mountNode ? createPortal(children, mountNode) : <>{children}</>;
};
