Created
July 27, 2020 14:21
-
-
Save mbelsky/92d31c6c1d76e41d1123f272dd369ffe 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 React, {useRef, useEffect} from 'react' | |
import {createPortal} from 'react-dom' | |
type PortalProps = { | |
children: React.ReactNode | |
} | |
function Portal({children}: PortalProps): JSX.Element { | |
const modalContainer = document.body | |
const modalElementRef = useRef<HTMLDivElement>() | |
function getModalElement(): HTMLDivElement { | |
if (!modalElementRef.current) { | |
modalElementRef.current = document.createElement('div') | |
} | |
return modalElementRef.current | |
} | |
useEffect(() => { | |
const modalElement = getModalElement() | |
modalContainer.appendChild(modalElement) | |
return (): void => { | |
modalContainer.removeChild(modalElement) | |
} | |
}, []) | |
return createPortal(children, getModalElement()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment