Sub topic 5
Building a modal dialog
This chapter builds a modal dialog on top of createPortal. It assumes you know function components, props and children, useState, useEffect and useRef, DOM event bubbling, and basic CSS positioning and z-index. It also assumes you have seen createPortal(children, container) and why portals avoid clipping and stacking problems. The goal here is a modal you could ship: it opens and closes, closes on backdrop click and Escape, locks page scroll, moves focus in and restores it, and announces itself to assistive technology.
What a modal has to do
A modal is a dialog that blocks interaction with the rest of the page until the user dismisses it. Rendering it through a portal solves only the visual part, because the dialog escapes parent overflow and z-index. The behavior is still your job:
- Render outside the parent DOM node, usually in
document.body. - Close on backdrop click, Escape, and an explicit close button.
- Prevent the page behind it from scrolling.
- Move keyboard focus into the dialog on open, keep it there, and return it to the triggering element on close.
- Expose the right roles and attributes to screen readers.
The sections below add these one at a time.
Step 1: The minimal portal modal
This is the smallest useful version. The backdrop and dialog become children of document.body, so no ancestor can clip or bury them.
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
);
}The inner stopPropagation stops clicks inside the dialog from reaching the backdrop's onClick. It works, but it has a side effect. React events bubble along the React tree, not the DOM tree, so stopPropagation also hides the click from every React ancestor of <Modal>. If a parent uses a click handler for analytics or for closing a menu, it will never see clicks inside the modal. The next step avoids that.
Step 2: A safer backdrop click
Compare the event target with the element that owns the handler. currentTarget is the backdrop, and target is whatever was actually clicked. They match only when the user clicks the backdrop itself.
function handleBackdropClick(event) {
if (event.target === event.currentTarget) {
onClose();
}
}With this check you can drop stopPropagation from the dialog. Parent handlers keep working, and clicks inside the dialog do not close it.
There is one more edge case. If the user presses the mouse inside the dialog, drags a text selection out onto the backdrop and releases, browsers fire click on the common ancestor, which is the backdrop. The modal closes unexpectedly. If this matters for your forms, listen to onMouseDown instead of onClick for the backdrop check.
Step 3: Controlling visibility
A modal that is always mounted wastes work and keeps stale state. The common pattern is an open prop that controls rendering. Hooks must still run on every render, so place them above the early return.
function Modal({ open, onClose, children }) {
// hooks go here, before any return
if (!open) return null;
return createPortal(/* ... */, document.body);
}Returning null unmounts the dialog content, so its internal state resets each time it opens. That is usually what you want for forms. If you need to keep state, hold it in the parent.
Step 4: Closing on Escape
Escape should work wherever focus is, so listen on document. This is the hook from the spine, extended with an enabled flag so the listener exists only while the modal is open.
import { useEffect } from 'react';
function useEscapeKey(onEscape, enabled = true) {
useEffect(() => {
if (!enabled) return;
function handleKeyDown(event) {
if (event.key === 'Escape') onEscape();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onEscape, enabled]);
}The cleanup function matters. Without it, every open adds another listener and closed modals keep reacting to Escape. If the parent passes an inline arrow function as onClose, the effect re-subscribes on every render. That is harmless but wasteful, and wrapping the callback in useCallback avoids it.
Step 5: Locking page scroll
When the modal opens, the page behind it should not scroll. The simple approach sets overflow: hidden on document.body and restores the previous value afterward.
function useScrollLock(locked) {
useEffect(() => {
if (!locked) return;
const previous = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = previous;
};
}, [locked]);
}Saving and restoring the previous value keeps the hook from clobbering styles set elsewhere. Two gotchas remain. Hiding the scrollbar makes the page width jump on desktop browsers, so some teams add matching padding-right. And if two modals are open at once, the first to close restores overflow too early. Nested modals need a shared counter, which is beyond this chapter.
Step 6: Focus management
Portals change where the dialog sits in the DOM, so the browser's natural tab order no longer places it next to the button that opened it. Without help, a keyboard user opens the modal and keeps tabbing through the page behind it. A modal needs three focus behaviors:
- On open, move focus into the dialog.
- While open, keep Tab and Shift+Tab inside it.
- On close, return focus to the element that was focused before.
The dialog container gets tabIndex={-1}. That makes it focusable by script but keeps it out of the tab order.
import { useEffect, useRef } from 'react';
const FOCUSABLE =
'a[href], button:not([disabled]), textarea:not([disabled]), ' +
'input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
function useFocusTrap(open, dialogRef) {
useEffect(() => {
if (!open) return;
const dialog = dialogRef.current;
const previouslyFocused = document.activeElement;
dialog.focus();
function handleKeyDown(event) {
if (event.key !== 'Tab') return;
const items = dialog.querySelectorAll(FOCUSABLE);
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items[items.length - 1];
const active = document.activeElement;
if (event.shiftKey && (active === first || active === dialog)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
}
dialog.addEventListener('keydown', handleKeyDown);
return () => {
dialog.removeEventListener('keydown', handleKeyDown);
if (previouslyFocused instanceof HTMLElement) previouslyFocused.focus();
};
}, [open, dialogRef]);
}The effect captures document.activeElement before moving focus, and the cleanup restores it. Because cleanup runs when open becomes false or the component unmounts, both ways of closing are covered.
Step 7: Roles and labels
role="dialog" tells assistive technology this is a dialog, and aria-modal="true" says content outside it is inert. A dialog also needs an accessible name. Point aria-labelledby at the visible title, using useId so the id is unique and stable between server and client.
The complete modal
This version combines every step. It also accepts a title so the dialog is always labeled.
import { useId, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
const FOCUSABLE =
'a[href], button:not([disabled]), textarea:not([disabled]), ' +
'input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
function useEscapeKey(onEscape, enabled) {
useEffect(() => {
if (!enabled) return;
const handle = (e) => {
if (e.key === 'Escape') onEscape();
};
document.addEventListener('keydown', handle);
return () => document.removeEventListener('keydown', handle);
}, [onEscape, enabled]);
}
function useScrollLock(locked) {
useEffect(() => {
if (!locked) return;
const previous = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = previous;
};
}, [locked]);
}
function useFocusTrap(open, dialogRef) {
useEffect(() => {
if (!open) return;
const dialog = dialogRef.current;
const previouslyFocused = document.activeElement;
dialog.focus();
function handleKeyDown(event) {
if (event.key !== 'Tab') return;
const items = dialog.querySelectorAll(FOCUSABLE);
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items[items.length - 1];
const active = document.activeElement;
if (event.shiftKey && (active === first || active === dialog)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
}
dialog.addEventListener('keydown', handleKeyDown);
return () => {
dialog.removeEventListener('keydown', handleKeyDown);
if (previouslyFocused instanceof HTMLElement) previouslyFocused.focus();
};
}, [open, dialogRef]);
}
export function Modal({ open, title, onClose, children }) {
const dialogRef = useRef(null);
const titleId = useId();
useEscapeKey(onClose, open);
useScrollLock(open);
useFocusTrap(open, dialogRef);
if (!open) return null;
return createPortal(
<div
className="backdrop"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div
ref={dialogRef}
className="dialog"
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
tabIndex={-1}
>
<h2 id={titleId}>{title}</h2>
{children}
<button type="button" onClick={onClose}>
Close
</button>
</div>
</div>,
document.body
);
}One ordering detail: useFocusTrap runs its effect after the first render in which open is true. By then the portal content is committed, so dialogRef.current is set. When open is false, the ref is null, and the effect returns before touching it.
Here is how a parent uses it, with the CSS that makes the backdrop cover the viewport.
import { useState } from 'react';
import { Modal } from './Modal';
export default function App() {
const [open, setOpen] = useState(false);
return (
<main style={{ overflow: 'hidden', height: 200 }}>
<button onClick={() => setOpen(true)}>Delete account</button>
<Modal open={open} title="Delete account?" onClose={() => setOpen(false)}>
<p>This cannot be undone.</p>
</Modal>
</main>
);
}.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: min(90vw, 480px);
max-height: 90vh;
overflow: auto;
}The main element in App has overflow: hidden and a small height on purpose. A modal rendered inline would be clipped there, but the portal version displays at full size.
The lifecycle at a glance
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Modal closes when clicking inside it | Backdrop handler has no target check | Compare `e.target` with `e.currentTarget` |
| Page still scrolls behind the modal | No scroll lock, or lock cleanup missing | Use `useScrollLock` and restore the old value |
| Escape still triggers after closing | Listener not removed | Return a cleanup from the effect |
| Focus lands on the page behind | No focus move or trap | Focus the dialog on open and trap Tab |
| "Rendered fewer hooks" error | Hooks placed after `if (!open) return null` | Call every hook before the early return |
| `document is not defined` on the server | Portal runs during server render | Create the portal only after mount, as covered in the server rendering chapter |
Where to go next
The modal here relies on portal event rules you have only touched on. The onMouseDown check on the backdrop and the decision to avoid stopPropagation come from the fact that React events bubble through the React tree. The following chapters explain that behavior in full, along with context and server rendering.
Exercise
A teammate adds onClick={(e) => e.stopPropagation()} to the dialog to stop backdrop closing. A parent component of <Modal> logs every click for analytics, and it no longer logs clicks inside the modal. Why, and what would you change?
Show answer
React events bubble along the React component tree, so a click inside the portal would normally reach the parent's onClick even though the DOM nodes are elsewhere. stopPropagation on the dialog halts that bubbling, so the parent never sees the event. Remove it and instead check event.target === event.currentTarget in the backdrop handler, so only direct backdrop clicks close the modal.
Exercise
In the complete Modal, why are useEscapeKey, useScrollLock and useFocusTrap called before if (!open) return null, and what would break if you moved them below it?
Show answer
React requires hooks to be called in the same order on every render. If they came after the early return, they would run only when open is true, so the hook count would change between renders and React would throw an error about a different number of hooks. Putting them first and giving each an enabled or open check inside its effect keeps the order stable.
Exercise
A user opens the modal with the keyboard from a "Delete account" button, presses Escape, and then finds focus at the top of the page. Which part of the code is responsible for returning focus to the button, and when does it run?
Show answer
The cleanup function returned by the effect in useFocusTrap. The effect saves document.activeElement before focusing the dialog, and the cleanup calls .focus() on that saved element. Cleanup runs when open changes to false or the component unmounts, so it covers closing via Escape, the backdrop or the Close button. If focus ends up at the top of the page, the saved element was probably not an HTMLElement or no longer exists.