31 lines
859 B
TypeScript
31 lines
859 B
TypeScript
"use client";
|
|
|
|
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] = useState(() => {
|
|
// This will be executed only on the initial render
|
|
// https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
|
|
return document.getElementById("root-portal") || 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);
|
|
};
|