React portals for rendering outside component tree

Maya Patel Jan 2026
2 tabs
import { ReactNode, useEffect, useState } from 'react'
import { createPortal } from 'react-dom'

interface PortalProps {
  children: ReactNode
  container?: Element
}

export function Portal({ children, container }: PortalProps) {
  const [mountNode, setMountNode] = useState<Element | null>(null)

  useEffect(() => {
    setMountNode(container || document.body)
  }, [container])

  return mountNode ? createPortal(children, mountNode) : null
}
2 files · typescript Explain with highlit

Portals render components outside their parent DOM hierarchy while maintaining React's component tree for context and events. I use portals for modals, tooltips, and dropdowns that need to escape overflow: hidden containers or z-index stacking contexts. ReactDOM.createPortal takes a component and a DOM node, rendering the component as a child of that node. Events bubble through the React tree, not the DOM tree, so click handlers work naturally. For modals, I render into a dedicated div at document root. Tooltips portal into a positioned container to avoid clipping. This technique solves CSS positioning nightmares while keeping component logic clean.