Portals in React — React Technical Interview Questions & Answers

Portals in React

Portals in React

  • createPortal(jsx, domNode) renders children into a DOM node outside the parent — typically document.getElementById('modal-root'). Modals, toasts, tooltips escape overflow:hidden and z-index wars. In the React tree, the modal still sits under the opener for context and events.
  • You still need to stop background scroll and handle focus trap for a real modal. Portal only solves where the DOM node lives.
  • Portals in React — modal markup still has React parents, but the div sits under #modal-root — escapes overflow:hidden.

Technical Interview Tip: Why modals use portals + event bubbling note.

Code Examples for Portals in React

Example

// Portal
import { createPortal } from "react-dom";

export default function Modal({ open, children }) {
  if (!open) return null;
  return createPortal(
    <div className="modal">{children}</div>,
    document.getElementById("modal-root")
  );
}

Portals in React — modal markup still has React parents, but the div sits under #modal-root — escapes overflow:hidden.

How to Explain Portals in React to an Interviewer

Explain Portals as if you are teaching a junior — definition, then one tiny UI.

Render into another DOM node. modal / tooltip.

Write 5–10 lines that use Portals and say what the UI does.

Show JSX Say the screen

What mistake do freshers make with Portals?

React tree (events/context) still parents.