Q17: What are React Portals and when should you use them?

Portals (ReactDOM.createPortal(child, container)) provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Used for modals, tooltips, and popovers to bypass CSS z-index and overflow: hidden parent clipping.

Rendering Modal via Portal
import ReactDOM from 'react-dom';

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div class="modal-overlay">{children}</div>,
    document.getElementById('modal-root') // Mounted to body root
  );
}

Modal renders inside #modal-root at the body level while retaining React parent-child context and event bubbling.

Key Takeaways
  • Renders HTML DOM output outside parent containers.

  • Events dispatched inside portals still bubble up through the React Virtual DOM component tree.

Knowledge Check

Does a click event originating inside a React Portal bubble up to its parent component in the React VDOM tree?