-
-
Save brunosabot/3110e062d9dc353ba3a47c28254ac6e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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