Modal example
- React course
- Intermediate
- Lesson 62/80
- 4 min
Learn to write a modal with portal that avoids overflow issues.
Modal example
In this lesson you will write a full modal example. The modal is controlled by an open/closed state; when open it renders via portal, when closed it does not render at all. Clicking the backdrop closes the modal.
The modal component renders two elements: a backdrop overlay and a content box. The backdrop is semi-transparent and covers the screen; the content box is centered.
State management lives in the parent; the modal only renders. This separation makes the modal reusable.
Backdrop overlay
The modal's backdrop overlay is a semi-transparent layer. It covers the screen and sits behind the content box. Clicking it closes the modal; clicking the content box does not.
To make this distinction, the content box uses stopPropagation; this stops the click from reaching the backdrop. Or the backdrop and content use separate click handlers.
The backdrop usually uses position: fixed and inset: 0 to cover the whole screen.
Practice Modal component
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 How is the modal controlled?
- useRef
- useMemo
- useState Correct answer
- useEffect
Explanation: The modal is controlled by an open/closed state.
2 When modal is open
if (!open) return null;
return createPortal(<div className="modal" onClick={____}><div className="content">{children}</div></div>, modalRoot);
if (!open) return null;
return createPortal(<div className="modal" onClick={onClose}><div className="content">{children}</div></div>, modalRoot);
Explanation: Clicking the backdrop calls onClose, closing the modal.
3 Modal example: match the terms
| Term | Meaning |
|---|---|
createPortal |
Renders into another node |
open |
Open/closed state |
onClose |
Close handler |
backdrop |
Background overlay |