React
Modal example
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.
Exercise 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.
Show example 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;
Test yourself
-
How is the modal controlled?
- useRef
- useMemo
- useState
- useEffect
Show answer
useState — The modal is controlled by an open/closed state.
-
When modal is open
if (!open) return null;
return createPortal(<div className="modal" onClick={____}><div className="content">{children}</div></div>, modalRoot);
Show answer
if (!open) return null;
return createPortal(<div className="modal" onClick={onClose}><div className="content">{children}</div></div>, modalRoot);
-
Modal example: match the terms
- createPortal
- Renders into another node
- open
- Open/closed state
- onClose
- Close handler
- backdrop
- Background overlay
Next lesson: Event bubbling