Skip to content

Instantly share code, notes, and snippets.

@mbelsky
Created July 27, 2020 14:21
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 mbelsky/92d31c6c1d76e41d1123f272dd369ffe to your computer and use it in GitHub Desktop.
Save mbelsky/92d31c6c1d76e41d1123f272dd369ffe to your computer and use it in GitHub Desktop.
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