Skip to content

Instantly share code, notes, and snippets.

@brunosabot
Created November 11, 2021 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunosabot/3110e062d9dc353ba3a47c28254ac6e1 to your computer and use it in GitHub Desktop.
Save brunosabot/3110e062d9dc353ba3a47c28254ac6e1 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
interface IModalPortalProps {
active: boolean;
children: React.ReactNode;
}
export default function ModalPortal({
active,
children,
}: IModalPortalProps): React.ReactPortal | null {
const elRef = useRef<HTMLDivElement>();
useEffect(() => {
if (window) {
elRef.current = window.document.createElement("div");
}
}, []);
useEffect(() => {
const modalRoot = window.document.getElementById("modal-root");
if (active && elRef.current && modalRoot !== null) {
const { current } = elRef;
modalRoot.appendChild(current);
return () => {
modalRoot.removeChild(current);
};
}
return () => {};
}, [active]);
if (elRef.current && active) {
return createPortal(children, elRef.current);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment