Summary - Portal
- React course
- Intermediate
- Lesson 64/80
- 5 min
Make a confirmation dialog a modal rendered outside the root via portal.
Summary - Portal
In this group you learned what a portal is, the modal example, and event propagation. createPortal renders a component to a different DOM node; open and onClose control the modal; stopPropagation stops content clicks from reaching the backdrop.
The portal lets elements like modals and dropdowns render without being affected by parent styles. Thanks to event propagation, the parent can manage state comfortably. In the last step you combine all three tools into a full modal.
Practice Summary modal
Complete the skeleton below. Write a Modal component; take { open, onClose, children }, return null if open is false, otherwise use createPortal to render <div className="modal" onClick={onClose}>{children}</div>. Export it.
Starter code
import { createPortal } from "react-dom";
// Write the Modal component hereSample solution
import { createPortal } from "react-dom";
function Modal({ open, onClose, children }) {
if (!open) return null;
return createPortal(
<div className="modal" onClick={onClose}>{children}</div>,
document.getElementById("modal-root")
);
}
export default Modal;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where do portal events go?
- Nowhere
- Body'ye
- To the React parent component Correct answer
- DOM'a
Explanation: Portal events bubble to the React parent.
2 Summary match
| Term | Meaning |
|---|---|
createPortal |
Renders into another node |
open |
Open/closed |
onClose |
Closing |
stopPropagation |
Stops the event |