2024-03-19 14:49:50 -06:00

26 lines
721 B
TypeScript

import { FC, PropsWithChildren, useEffect, useState } from "react";
import { createPortal } from "react-dom";
interface IProps {
className?: string;
el?: string;
}
export const Portal: FC<PropsWithChildren<IProps>> = (
{ children, className = "root-portal", el = "div" },
) => {
const [container, setContainer] = useState<HTMLElement>();
useEffect(() => {
const container = document.createElement(el);
container.classList.add(className);
document.body.appendChild(container);
setContainer(container);
return () => {
document.body.contains(container) && document.body.removeChild(container);
};
}, [className, el]);
return container && createPortal(children, container);
};