Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

custom portal react

import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'

export function Portal({ children, selector }) {
  const ref = useRef()
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    ref.current = document.querySelector(selector)
    setMounted(true)
  }, [selector])

  return mounted ? createPortal(children, ref.current) : null
}

// Usage
<Portal selector="#modal">
  <h1> Hey </h1>
</Portal>
 
PREVIOUS NEXT
Tagged: #custom #portal #react
ADD COMMENT
Topic
Name
5+9 =