import type { FC, HTMLAttributes } from 'react';
import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';

export interface ClientPortalProps extends HTMLAttributes<HTMLElement> {
  selector?: string;
}

const ClientPortal: FC<ClientPortalProps> = ({ children, selector = 'body' }) => {
  const ref = useRef<Element | null>(null);

  useEffect(() => {
    ref.current = document.querySelector(selector);
  }, [selector]);

  return ref.current ? createPortal(children, ref.current) : null;
};

export default ClientPortal;
