Created
March 12, 2020 11:35
-
-
Save mrwest808/853e0435ba34f4ce4a4687282e39e7f5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { ReactNode, useRef, useEffect } from 'react'; | |
| import { createPortal } from 'react-dom'; | |
| interface PortalProps { | |
| children: ReactNode; | |
| id: string; | |
| } | |
| export default function Portal({ children, id }: PortalProps) { | |
| const elRef = useRef<HTMLElement>(null); | |
| function getElement() { | |
| if (!elRef.current) { | |
| // @ts-ignore | |
| elRef.current = document.createElement('div'); | |
| } | |
| return elRef.current!; | |
| } | |
| useEffect(() => { | |
| const mountElement = document.getElementById(id); | |
| mountElement?.appendChild(getElement()); | |
| return () => { | |
| mountElement?.removeChild(getElement()); | |
| elRef.current?.remove(); | |
| }; | |
| }, [id]); | |
| return createPortal(children, getElement()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment