Sub topic 5
Building a modal dialog
This chapter assumes you know function components, props and children, useState and useEffect, basic DOM concepts, and CSS positioning with z-index. A modal is the standard use case for createPortal, so this chapter builds one step by step.
Why a modal needs a portal
A modal must cover the whole page. If you render it inline, an ancestor with overflow: hidden can clip it. An ancestor that creates a stacking context, such as one with transform or position: relative; z-index: 1, can bury it under other content. The usual fix is to render the modal into document.body, outside those ancestors, while keeping it in the same React tree.
The minimal modal
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
{children}
</div>
</div>,
document.body
);
}This component has four parts:
createPortal(child, container)renderschildinsidecontainerin the DOM. Here the container isdocument.body.- The
.backdropelement is the dimmed layer. Clicking it callsonClose. - The
.dialogelement holds the content. Its click handler callsstopPropagation, so a click inside the dialog does not reach the backdrop and close the modal. role="dialog"andaria-modal="true"tell assistive technology that this is a modal dialog.
Styling the layers
The backdrop is fixed to the viewport and sits above normal content.
.backdrop {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: rgba(0, 0, 0, 0.5);
z-index: 1000;
}
.dialog {
background: white;
padding: 1.5rem;
border-radius: 8px;
max-width: 28rem;
}Because the portal target is document.body, z-index: 1000 competes only with other children of the body. The stacking contexts of your app's inner components no longer matter.
Controlling the modal from a parent
The parent owns the open state. The modal does not decide when it appears.
import { useState } from 'react';
function App() {
const [open, setOpen] = useState(false);
return (
<div style={{ overflow: 'hidden', height: 100 }}>
<button onClick={() => setOpen(true)}>Open</button>
{open && <Modal onClose={() => setOpen(false)}>Hello from a portal</Modal>}
</div>
);
}The <div> with overflow: hidden would clip an inline dialog. The portal output is not inside that <div> in the DOM, so the clipping does not apply. When open becomes false, React unmounts the Modal, and the portal content is removed from document.body.
Closing with Escape
Keyboard users expect Escape to close a modal. A document-level listener handles this, and the cleanup function removes it.
import { useEffect } from 'react';
function useEscapeKey(onEscape) {
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') onEscape();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onEscape]);
}Call useEscapeKey(onClose) inside Modal. Because onClose is a dependency, an inline arrow function from the parent makes the effect re-subscribe on every render. That works but is wasteful. Wrap onClose in useCallback in the parent if it matters.
How the pieces fit
In the React tree, Modal is a child of the container. In the DOM, its output is a child of document.body.
Common mistakes
- Forgetting
stopPropagationon the dialog. Every click inside the dialog then closes the modal. - Rendering the portal while
document.bodyis unavailable. On the server there is nodocument. A later chapter covers this. - Leaving listeners behind. Always return a cleanup function from effects that add document listeners.
- Relying on
z-indexalone for focus. A modal that looks on top still lets Tab move to the page behind it. Focus management is covered in the accessibility chapter.
Exercise
A modal rendered with createPortal(..., document.body) still appears clipped inside a parent with overflow: hidden. The CSS for .backdrop uses position: absolute instead of position: fixed. Why might that cause clipping or misplacement, and what is the fix?
Show answer
Inside the body, an absolutely positioned backdrop is placed relative to its nearest positioned ancestor, or to the initial containing block, and it scrolls with the page. It does not cover the viewport reliably. Use position: fixed; inset: 0 so the backdrop is sized to the viewport regardless of scrolling. The portal removes the ancestor's clipping, but the backdrop still needs correct positioning.
Exercise
Why does the .dialog element call e.stopPropagation() in its onClick?
Show answer
The backdrop is the dialog's parent and closes the modal on click. Clicks inside the dialog bubble up to the backdrop. Stopping propagation at the dialog prevents those clicks from triggering onClose.