React Portals: Modals, Tooltips & Interview Use Cases
⚛ ری‌اکت

React Portals: Modals, Tooltips & Interview Use Cases

Render children into a different DOM node while preserving React tree context and events.

BugCast Admin··۵ دقیقه مطالعه

Portals let you break out of parent DOM hierarchy for modals and overlays while keeping event bubbling and Context in the React tree.

Common Interview Questions

Q: What problem do portals solve?

Answer: Parent overflow: hidden or z-index stacking contexts trap modals. Portals mount UI elsewhere in the DOM but remain logically under the same React parent.


import { createPortal } from "react-dom";

createPortal(
  <Modal>{children}</Modal>,
  document.getElementById("modal-root")
);

Q: Do events bubble through portals?

Answer: Yes — React events bubble through the React component tree, not the DOM tree. A click inside a portal still triggers handlers on ancestors in JSX.

Q: Can portals access Context?

Answer: Yes. Context is based on React tree position, not DOM position. Portal children see the same providers as siblings would.

Q: Accessibility considerations?

Answer: Trap focus inside modals, restore focus on close, use aria-modal, and pair with role="dialog". Consider libraries like Radix or Headless UI.

Key Points for Interviews

  • createPortal(children, domNode) is the API

  • Event bubbling follows React hierarchy

  • Essential for modals, tooltips, and dropdowns

  • SSR needs a stable mount target element

  • Does not escape Context or error boundaries above portal

#portals#modals#interview

مطالب مرتبط