26 lines
684 B
TypeScript
26 lines
684 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.removeChild(container);
|
|
};
|
|
}, [className, el]);
|
|
|
|
return container && createPortal(children, container);
|
|
};
|