InPortal


The InPortal component is a React component used for rendering children into a 'portal' identified by an element in the DOM outside of the parent component's DOM hierarchy.

Props

  • id: string - The id of the target element in the DOM where the portal should be rendered.
  • children: ReactNode - The children elements to be rendered inside the portal.

Usage

import type { ReactElement, ReactNode } from 'react'
import { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'

interface InPortalProps {
   id: string
   children: ReactNode
}

export function InPortal({ id, children }: InPortalProps): ReactElement | null {
   const [hasMounted, setHasMounted] = useState(false)
   useEffect(() => {
      setHasMounted(true)
   }, [])
   if (!hasMounted)
      return null

   const element = document.querySelector(`#${id}`)

   if (!element)
      throw new Error(`No element with id "${id}" found in the document`)

   return ReactDOM.createPortal(
      children,
      element,
   )
}

Component

import type { ReactElement, ReactNode } from 'react'
import { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'

interface InPortalProps {
   id: string
   children: ReactNode
}

export function InPortal({ id, children }: InPortalProps): ReactElement | null {
   const [hasMounted, setHasMounted] = useState(false)
   useEffect(() => {
      setHasMounted(true)
   }, [])
   if (!hasMounted)
      return null

   const element = document.querySelector(`#${id}`)

   if (!element)
      throw new Error(`No element with id "${id}" found in the document`)

   return ReactDOM.createPortal(
      children,
      element,
   )
}