Lesson 19 of 80
Render a component's output into a completely different DOM node than its parent — the tree stays logical in React, but the pixels land somewhere else entirely.
10 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
A modal is rendered via createPortal into a DOM node outside the app root. A click inside it needs to trigger an onClick handler on a logical parent defined in JSX. Does that still work?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Normally a component's rendered output is inserted into the DOM exactly where its parent put it. createPortal breaks that: the component still lives in the React tree wherever you wrote it (props, context, event bubbling all work normally), but its actual DOM output is inserted wherever you point it.
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById("modal-root") // a div outside the normal app root
);
}
Modal might be rendered deep inside a component with overflow: hidden or a constrained z-index stacking context — without a portal, the modal would be visually clipped or trapped behind other content. The portal lets its DOM node sit at the top level, free of the parent's CSS constraints, while Modal itself stays a normal, logical child in React's tree.
createPortal(<Modal />, document.getElementById('modal-root')) — render this subtree into a different DOM node.
overflow: hidden or stacking context are the textbook cases — not a general-purpose tool for arbitrary layout.createPortal runs — a common setup is a static <div id="modal-root"> sitting next to the app's root <div id="root"> in index.html."How would you build a modal that isn't clipped by a parent's overflow:hidden?" is a very concrete, common scenario, and portals are the textbook-correct React answer — recognizing this as a DOM-placement problem (not a CSS-only problem) is the actual signal.