ReactPortalError Fix2026 Updated

React Portal Not Rendering— createPortal Fixed [2026]

Also covers: target DOM missing · SSR hydration mismatch · z-index stacking · event bubbling · reusable modal pattern

January 20265 min readReact 18/19 · Next.js · TypeScript

⚡ Common Problems

Error
// Portal renders nothing — target element not in DOM
const portal = createPortal(<Modal />, document.getElementById("portal-root"))
// → null if #portal-root doesn't exist in HTML

// Next.js SSR error:
ReferenceError: document is not defined

✅ Fix — add target to HTML and guard against SSR

app/layout.tsx — add portal root
<body>
  {children}
  <div id="portal-root" />   {/* ← target for all portals */}
</body>

Why React Portals Fail to Render

React portals render to a DOM node outside your component's natural DOM position. Three things must all be true: the target DOM node must exist when the portal mounts, createPortal must run client-side (not during SSR), and the target node must not itself be constrained by CSS overflow or stacking.

1

Ensure the Target DOM Element Exists

Portal renders null — getElementById returns null
2 min
Add portal-root to your HTML / Next.js layout
<!-- index.html (Vite/CRA) -->
<body>
  <div id="root"></div>
  <div id="portal-root"></div>  <!-- ← add this -->
</body>

{/* app/layout.tsx (Next.js App Router) */}
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <div id="portal-root" />   {/* ← add after children */}
      </body>
    </html>
  )
}

{/* Usage in a component */}
import { createPortal } from "react-dom"

function Modal({ children }: { children: React.ReactNode }) {
  const el = document.getElementById("portal-root")
  if (!el) return null                     // guard if element somehow missing
  return createPortal(children, el)
}
2

Fix SSR Hydration Mismatch with Portals

document is not defined in Next.js
3 min

React portals use the browser DOM — they don't work during server-side rendering. Guard with a mounted state that is only set after the component mounts on the client.

SSR-safe portal component
"use client"

import { createPortal } from "react-dom"
import { useState, useEffect, type ReactNode } from "react"

interface PortalProps {
  children: ReactNode
  targetId?: string
}

export function Portal({ children, targetId = "portal-root" }: PortalProps) {
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)       // only true after client-side mount
    return () => setMounted(false)
  }, [])

  // ✅ During SSR: mounted = false → render nothing → no hydration mismatch
  // After mount: render through portal
  if (!mounted) return null

  const target = document.getElementById(targetId)
  if (!target) return null

  return createPortal(children, target)
}

// Usage:
function Modal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  if (!isOpen) return null

  return (
    <Portal>
      <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
        <div className="bg-white rounded-xl p-6 max-w-md w-full">
          <button onClick={onClose}>Close</button>
        </div>
      </div>
    </Portal>
  )
}
3

Fix z-index and Stacking Context Issues

Portal modal hidden behind other elements
3 min
Portal target and z-index setup
/* globals.css — ensure portal-root is above everything */
#portal-root {
  position: relative;
  z-index: 9999;          /* above all page content */
}

/* Modal overlay — fixed to viewport */
.modal-overlay {
  position: fixed;
  inset: 0;               /* top/right/bottom/left: 0 */
  background: rgba(0, 0, 0, 0.5);
  z-index: 50;            /* Tailwind z-50 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* In Tailwind: */
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
  <div className="relative bg-white rounded-xl shadow-2xl p-6 z-10">
    {/* modal content */}
  </div>
</div>

The portal target at document.body level already escapes all parent overflow and stacking contexts. As long as you use position: fixed with a high z-index on the modal overlay, it will appear above all page content.

4

Understand Event Bubbling Through Portals

Click events propagating unexpectedly
2 min

React portal events bubble through the React component tree (not the DOM tree). A click inside a portal bubbles to the React parent that rendered the portal. Stop propagation to prevent this when needed.

Event bubbling in portals
function App() {
  return (
    // ✅ This onClick WILL fire when clicking inside the portal modal
    // because React events bubble through the React tree, not the DOM tree
    <div onClick={() => console.log("App clicked!")}>
      <Modal />   {/* Modal content is at document.body in DOM, but here in React tree */}
    </div>
  )
}

// Fix — stop propagation inside the modal if you don't want parent to fire
function Modal() {
  return createPortal(
    <div
      className="fixed inset-0 bg-black/50 z-50"
      onClick={(e) => e.stopPropagation()}  // ← stop bubbling to React parent
    >
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        Modal content
      </div>
    </div>,
    document.getElementById("portal-root")!
  )
}
5

Build a Reusable Modal Portal Component

Production-ready pattern with accessibility
5 min
components/modal.tsx — complete reusable portal modal
"use client"

import { createPortal } from "react-dom"
import { useEffect, useState, type ReactNode } from "react"

interface ModalProps {
  isOpen: boolean
  onClose: () => void
  children: ReactNode
  title?: string
}

export function Modal({ isOpen, onClose, children, title }: ModalProps) {
  const [mounted, setMounted] = useState(false)

  useEffect(() => { setMounted(true) }, [])

  // Close on Escape key
  useEffect(() => {
    if (!isOpen) return
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose()
    }
    document.addEventListener("keydown", handler)
    return () => document.removeEventListener("keydown", handler)
  }, [isOpen, onClose])

  // Lock body scroll when open
  useEffect(() => {
    if (isOpen) document.body.style.overflow = "hidden"
    return () => { document.body.style.overflow = "" }
  }, [isOpen])

  if (!mounted || !isOpen) return null

  return createPortal(
    <div
      className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"
      onClick={onClose}   // close on backdrop click
      role="dialog"
      aria-modal="true"
      aria-label={title}
    >
      <div
        className="bg-white rounded-2xl shadow-2xl max-w-lg w-full p-6"
        onClick={e => e.stopPropagation()}  // prevent backdrop close
      >
        {title && <h2 className="text-lg font-bold mb-4">{title}</h2>}
        {children}
      </div>
    </div>,
    document.getElementById("portal-root")!
  )
}

Prevention

Frequently Asked Questions

Why is my React portal not rendering anything?+
The most common cause is that the target DOM element does not exist when createPortal runs. If you pass document.getElementById('portal-root') and that element is not in your HTML, the portal renders to null and nothing appears. Ensure the target element exists in your index.html or layout.tsx before the portal mounts.
What is a React portal used for?+
Portals render a React component's DOM output into a different DOM node than the parent component's DOM node. The classic use case is modals, tooltips, and dropdown menus — you render them at the document.body level to escape overflow: hidden and z-index stacking contexts of parent elements.
How do I use React portals with Next.js?+
In Next.js, document is not available during server-side rendering. Guard createPortal with a mounted state using useState and useEffect. Only call createPortal after the component has mounted (client-side). Or use isMounted state to conditionally render the portal.
Does event bubbling work through React portals?+
Yes — React portals use synthetic events, which bubble through the React component tree, not the DOM tree. So a click inside a portal modal will bubble up to the React parent component that rendered the portal, even if the DOM node is at document.body. This is usually the desired behaviour.
Why does my portal modal still get clipped by overflow: hidden?+
The portal's React output goes into the target DOM node (usually document.body), but if the target node itself has overflow: hidden or a stacking context constraint, the content is still clipped. Always render portals into a clean element appended directly to document.body, not into a container inside your main React root.
Can I have multiple React portals on the same page?+
Yes. Each createPortal call targets a specific DOM node. You can have multiple portals pointing to the same node (common for modals) or different nodes. Stack order between portal contents is determined by DOM insertion order and z-index CSS.

Need Expert Help?

We Build React Components for Production

Softplix engineers build accessible, production-grade React components including modals, tooltips, and overlays. Let us help.

Talk to an Engineer