File size: 569 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'

type PortalProps = {
  children: React.ReactNode
  type: string
}

export const Portal = ({ children, type }: PortalProps) => {
  const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)

  useEffect(() => {
    const element = document.createElement(type)
    document.body.appendChild(element)
    setPortalNode(element)
    return () => {
      document.body.removeChild(element)
    }
  }, [type])

  return portalNode ? createPortal(children, portalNode) : null
}