import { FC, PropsWithChildren, useEffect, useState } from "react"; import { createPortal } from "react-dom"; interface IProps { className?: string; el?: string; } export const Portal: FC> = ( { children, className = "root-portal", el = "div" }, ) => { const [container] = useState(() => { // This will be executed only on the initial render // https://reactjs.org/docs/hooks-reference.html#lazy-initial-state return document.createElement(el); }); // todo: this smells. appending the same element? useEffect(() => { container.classList.add(className); document.body.appendChild(container); return () => { document.body.removeChild(container); }; }, [className, container]); return createPortal(children, container); };