Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active August 16, 2021 02:08
Show Gist options
  • Select an option

  • Save itsMapleLeaf/edc318f4f4744da36c429787fa47292d to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/edc318f4f4744da36c429787fa47292d to your computer and use it in GitHub Desktop.
portal
import { ReactNode, useEffect, useRef } from "react"
import { createPortal } from "react-dom"
export function Portal({ children }: { children: ReactNode }) {
const containerRef = useRef<Element>()
if (!containerRef.current) {
containerRef.current = document.createElement("react-portal")
document.body.append(containerRef.current)
}
useEffect(() => () => containerRef.current!.remove(), [])
return createPortal(children, containerRef.current)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment