Design an Accessible Dialog – Frontend System Design

We’ll walk through the frontend system design for a reusable modal dialog. Our goal is a component that opens from a trigger, traps focus, locks the page behind it, and restores the user’s place on close. This is not a “draw a centered card” interview. Interviewers treat it as an accessibility and state-machine problem. Put simply, the task is to design an accessible dialog that keyboard and screen reader users can trust.
You’ll see the public API, the open/close workflow, how we make the rest of the page inert, and the edge cases that separate a styled overlay from a real dialog. We’ll stay at component scale — one top-layer dialog, a handful of focusable nodes, and a scroll lock — not a fake Netflix backend.
Problem Statement
Design a modal / dialog that overlays the page.
Requirements:
- Opens from a button, closes via X, Cancel, Escape, or (optionally) backdrop click
- Focus is trapped inside while open and restored on close
- The rest of the page is inert (no click, no tab)
- Works for confirm, form, and large content
This interview is almost entirely accessibility.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Modal (must interact) or non-modal (popover)? | Modal. |
| 2 | Stack of modals? | Support one. Mention a stack if they push. |
| 3 | Scroll locking? | Yes. The page behind shouldn’t scroll. |
Ask two more if you have time: does the form survive a reopen, and is backdrop click allowed on a destructive confirm. A strong answer names the default (one modal, scroll locked, backdrop optional) and only adds a stack if the interviewer pushes.
Requirements
Functional Requirements
- Open from a trigger button; close via X, Cancel, Escape, or optional backdrop click
- Trap Tab / Shift+Tab inside the dialog while open
- Restore focus to the trigger on close
- Make the rest of the page inert (no click, no tab, no scroll)
- Support three content shapes: confirm, form, and large scrollable body
- Keep dialog content mounted if a form should survive a reopen
Non-Functional Requirements
- Open and close in one frame; no layout jump when the scrollbar disappears
- Keyboard-only use is a first-class path, not a follow-up
- Honor
prefers-reduced-motion— skip enter/exit animation - Work with a date picker or combobox nested inside the dialog
- Survive mobile keyboards resizing the visual viewport
Scalability Estimates
A modal is a single top-layer surface. The numbers that matter are focusable nodes, lock/unlock cost, and how often the trap list goes stale — not daily active users.
| Metric | Estimate | Calculation | Notes |
|---|---|---|---|
| Open dialogs | 1 | One top-layer dialog | Mention a stack of 2–3 if they push. Only the top dialog traps focus. |
| Focusable nodes inside | 8–20 | Title, close, 2–8 fields, 2 actions | Recalc after children mount or a picker opens. |
| Trap work per Tab | O(n) | n = cached focusable count | Cache the list. Do not querySelectorAll on every keydown. |
| Scrollbar compensation | ~15px | innerWidth - clientWidth |
Pad document.body so the page does not shift when overflow is hidden. |
| Enter / exit motion | 150–250ms | CSS opacity + transform | Skip entirely when prefers-reduced-motion: reduce. |
| Portal target | 1 host | Render into document.body |
Avoids overflow: hidden ancestors clipping the overlay. |
Component API
type ModalProps = {
open: boolean;
onClose: () => void;
title: string;
children: React.ReactNode;
closeOnBackdrop?: boolean;
initialFocusRef?: React.RefObject<HTMLElement>;
};
<Modal>
<Backdrop />
<Dialog>
<Header /> // title + close
<Body />
<Footer /> // actions
</Dialog>
</Modal>
Portal to document.body. Controlled open from the parent.
Keep the dialog controlled. The parent owns open so a route change, a successful submit, or a stack manager can close it without the dialog reaching into app state. Uncontrolled defaultOpen is a footgun in an interview — skip it unless they ask.
closeOnBackdrop defaults to false on destructive confirms and true on lightweight forms. Never make backdrop click the only close path. initialFocusRef is how a form modal lands on the first invalid field instead of the close button.
Three variants share this API:
- Confirm: short copy, two actions,
role="alertdialog"only if the user must decide now (delete, discard). - Form: fields in
Body, submit inFooter,initialFocusRefon the first input. - Large content: scrollable
Body, stickyHeaderandFooter, so actions stay on screen.
Frontend Architecture Overview
A modal is a small state machine with a large accessibility surface. The view is four pieces — Backdrop, Dialog, Header/Body/Footer — but the real work lives in a Focus Manager and a Scroll Lock that sit outside the JSX. Interviewers want to hear that split. If focus restore and inert live inside the Dialog render, you will miss a close path.
At a high level the parent sets open, a portal mounts the overlay on document.body, and a Modal Manager runs the open sequence: snapshot focus, move focus in, inert the app root, lock scroll. Close is the inverse, always, even if the user hit Escape, the X, Cancel, or the backdrop. One function, four entry points.
There is no heavy Network Manager here. A confirm that hits a server posts through the same request helper the rest of the app uses. The dialog does not fetch. If you invent a chat-scale data layer for a modal, the interviewer will pull you back to focus.
Component Structure and Responsibilities
- Modal: Controlled shell. Portals children, owns the open/close effect, wires Escape and backdrop. Renders nothing when
openis false unlesskeepMountedis set for a form that must survive. - Backdrop: Full-viewport layer under the dialog. Listens for pointer down on itself, not click, so a drag that starts in the dialog and ends on the dimmer does not close. Optional.
- Dialog: The labelled surface.
role="dialog",aria-modal="true",aria-labelledbypointing at the title id. This is the focus-trap root. - Header: Title plus the close button. The close button is always a real
<button>with an accessible name (“Close”), not a bare × span. - Body: Confirm copy, a form, or a scroll region. If content is tall, Body is the only scrolling pane. Header and Footer stay put.
- Footer: Primary and secondary actions. Primary is the last tab stop in a confirm so Enter on a focused field and Tab-to-OK both feel natural.
- Focus Manager: Snapshots
document.activeElement, moves focus in, traps Tab, restores on close. Not a React component — a module the Modal effect calls. - Scroll Lock: Sets
overflow: hiddenondocument.body, adds padding equal to the scrollbar width, and on iOS pinsposition: fixedwhile rememberingwindow.scrollY.
Modal Manager and Data Flow
The Modal Manager is a thin store, not a network layer. It holds open, the title id, whether backdrop close is allowed, and a pointer to the trigger. If the interviewer asks for a stack, the manager becomes an array of descriptors and only the last item is active. Lower dialogs stay mounted and visible but they do not receive Tab or Escape.
Side effects stay in the manager:
- Register and unregister the document
keydownlistener for Escape (capture phase, so a nested popover can stop it first) - Call Focus Manager and Scroll Lock on open and close
- Toggle
inerton the app root sibling (oraria-hiddenifinertis not available) - Announce open/close to a polite live region only if the title is not already focused
Open and Close Workflow
- The user activates a trigger. The parent sets
opento true. - Modal portals Backdrop + Dialog to
document.bodyand generates a stable title id. - Focus Manager stores
document.activeElementas the restore target. - Scroll Lock measures the scrollbar, hides overflow, and compensates padding.
- The app root sibling gets
inert(oraria-hidden="true"). - Focus moves to
initialFocusRef, else the first tabbable, else the close button, else the Dialog container. - Tab / Shift+Tab cycle inside Dialog. Escape, X, Cancel, or (if allowed) backdrop down call the same
onClose. - On close: undo inert, unlock scroll, restore focus to the trigger. If the trigger unmounted, focus the nearest landmark or
document.body.
Native <dialog> plus showModal() gives you the top layer, Escape, and a focus trap in modern browsers. In an interview, say you’d use it (or Radix / React Aria) and still know the steps above. The native element does not label itself, does not lock iOS scroll, and does not restore focus if you close from a route change — you still write those pieces.
Focus and Inert
- On open: remember
document.activeElement. - Move focus to the first focusable (or
initialFocusRef, or the close button). - Tab / Shift+Tab cycle inside the dialog. This is the trap.
- Set
aria-hidden(or theinertattribute) on the app root siblings. - Lock body scroll (
overflow: hidden). - On close: undo all of that and restore focus to the trigger.
Native <dialog> plus showModal() gives you the top layer, Escape, and a focus trap in modern browsers. In an interview, say you’d use it (or Radix / React Aria) and still know the steps above.
Building the top layer

If you cannot use <dialog>, you are rebuilding three browser features:
- Portal.
createPortal(node, document.body). The React tree stays under the opener (so context works); the DOM node sits whereoverflow: hiddenand az-index: 2header cannot trap it. - Stack. A module-level array of descriptors
{ id, onClose }. Open pushes. Close pops. Escape and the click-on-backdrop call the top descriptor only. z-index = base + index. Two dialogs is the follow-up (confirm inside a form); a single booleanopenwill lose the first dialog’s state if you unmount it. - Focus trap. On Tab from the last tabbable,
preventDefaultand focus the first. Inverse for Shift+Tab. Recompute the tabbable list when the body mutates (MutationObserveror on every Tab if the dialog is small). Restore focus to the recorded trigger on close, or to the dialog underneath if the stack is not empty.
The backdrop is a sibling behind the panel, not a parent that wraps the page. Clicking it closes if closeOnBackdrop is true; mousedown-inside / mouseup-outside must not count as a backdrop click (record the mousedown target).
The trap is the part people get wrong. You do not “disable tab on the page.” You keep a cached list of tabbable nodes inside the dialog and, on Tab from the last one, move to the first. On Shift+Tab from the first, move to the last. Radio groups count as one tab stop (the checked radio). Disabled, hidden, and aria-hidden descendants are not in the list.
inert on the app root is better than aria-hidden. It blocks click, Tab, and find-in-page on supporting browsers. Do not set aria-hidden on an ancestor of the dialog — that hides the dialog from the accessibility tree too. Hide siblings of the portal host, not the host itself.
Scroll lock is two platforms. On desktop, overflow: hidden plus scrollbar padding is enough. On iOS, overflow on body does not stop the page from rubber-banding; you set position: fixed; top: -scrollY on open and window.scrollTo(0, scrollY) on close. Measure the visual viewport when the keyboard opens so a form modal does not sit under the keys.
State and Data Flow
A modal has almost no server state and a lot of ephemeral UI state. Keep that split obvious.
- The parent holds
openand any form values that must outlive the overlay. - The user action (trigger click, route, or programmatic
openConfirm()) setsopen. - Modal’s effect runs the Focus Manager and Scroll Lock. No network yet.
- If the dialog is a form or confirm, submit goes through the app’s existing request helper. The dialog shows pending on the primary button and does not close until the promise settles — or it closes optimistically and the parent toasts a failure.
- Any close path calls the same
onClose. The effect teardown restores focus and scroll even if the parent unmounted the tree mid-animation. - Errors stay in the dialog (inline on the field or a banner in Body). Do not trap the user in a broken overlay with no close button.
If you need a stack, the manager is an array. Pushing a second dialog does not unmount the first. Escape and the trap attach only to the top descriptor. Closing the top one restores focus to the control in the dialog below, not all the way back to the original page trigger.
Data Model
The model is the dialog’s runtime snapshot plus a tiny descriptor if you mention a stack. Keep it serializable enough to log, not to persist.
type ModalVariant = "confirm" | "form" | "large";
type FocusSnapshot = {
trigger: HTMLElement | null;
lastActive: HTMLElement | null;
};
type ScrollSnapshot = {
overflow: string;
paddingRight: string;
scrollY: number;
usedPositionFixed: boolean;
};
type ModalDescriptor = {
id: string;
variant: ModalVariant;
titleId: string;
closeOnBackdrop: boolean;
keepMounted: boolean;
};
type ModalState = {
open: boolean;
stack: ModalDescriptor[]; // length 0 or 1 unless they ask for a stack
focus: FocusSnapshot | null;
scroll: ScrollSnapshot | null;
pendingAction: "submit" | "close" | null;
};
FocusSnapshot.trigger is what you restore to. lastActive is a fallback if the trigger node is gone. ScrollSnapshot lets you undo the lock without guessing the page’s original overflow. pendingAction disables the primary button and keeps Escape from double-firing a close while a confirm request is in flight.
API Design
For a component interview the public API is the props and a small hook, not a fleet of REST routes. If the modal confirms a destructive action, one POST is enough. Say that out loud so the interviewer knows you are not overbuilding.
| Action | Method / Endpoint | Description |
|---|---|---|
| Open dialog | open prop / modal.open(id) |
Parent sets controlled open. Hook form is useful for a stack. |
| Close dialog | onClose() |
X, Cancel, Escape, optional backdrop. Always the same function. |
| Move initial focus | initialFocusRef |
Form field or the destructive action, never a random div. |
| Confirm on the server | POST /v1/confirmations | Body { actionId, resourceId }. Return { ok: true }. Dialog closes on 2xx. |
| Cancel in-flight confirm | AbortController |
If the user hits Escape while pending, abort and leave the dialog open with an error. |
Example: Opening, Trapping, and Restoring Focus
function useModalFocus(open: boolean, rootRef: RefObject<HTMLElement>, restoreRef: RefObject<HTMLElement | null>) {
useEffect(() => {
if (!open || !rootRef.current) return;
restoreRef.current = document.activeElement as HTMLElement | null;
const focusable = getFocusable(rootRef.current);
(focusable[0] ?? rootRef.current).focus();
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Tab" || !rootRef.current) return;
const nodes = getFocusable(rootRef.current);
if (nodes.length === 0) {
event.preventDefault();
return;
}
const first = nodes[0];
const last = nodes[nodes.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("keydown", onKeyDown);
restoreRef.current?.focus();
};
}, [open, rootRef, restoreRef]);
}
function getFocusable(root: HTMLElement): HTMLElement[] {
const selector = "a[href], button:not([disabled]), textarea, input:not([type='hidden']), select";
return Array.from(root.querySelectorAll<HTMLElement>(selector)).filter((el) => {
return el.offsetParent !== null && !el.getAttribute("aria-hidden");
});
}
Cache getFocusable and refresh it with a MutationObserver when a date picker mounts inside the body. Refreshing on every Tab is the junior version; it is correct and slow enough to mention as the thing you would not ship.
Optimizations
The dialog is cheap to render. The costs that show up are layout shift from the scrollbar, a stale focus list, and unmounting a form on every close. Fix those with one effect and a keep-mounted flag — not a virtualizer.
Scrollbar compensation and iOS lock
function lockScroll(): ScrollSnapshot {
const body = document.body;
const scrollbar = window.innerWidth - document.documentElement.clientWidth;
const snapshot: ScrollSnapshot = {
overflow: body.style.overflow,
paddingRight: body.style.paddingRight,
scrollY: window.scrollY,
usedPositionFixed: /iPhone|iPad|iPod/.test(navigator.userAgent),
};
body.style.overflow = "hidden";
if (scrollbar > 0) {
body.style.paddingRight = `${scrollbar}px`;
}
if (snapshot.usedPositionFixed) {
body.style.position = "fixed";
body.style.top = `-${snapshot.scrollY}px`;
body.style.width = "100%";
}
return snapshot;
}
function unlockScroll(snapshot: ScrollSnapshot) {
const body = document.body;
body.style.overflow = snapshot.overflow;
body.style.paddingRight = snapshot.paddingRight;
if (snapshot.usedPositionFixed) {
body.style.position = "";
body.style.top = "";
body.style.width = "";
window.scrollTo(0, snapshot.scrollY);
}
}
Call lockScroll in the same effect that moves focus so the user never sees a one-frame shift. Pair it with prefers-reduced-motion: if reduced, set data-motion="none" on the dialog and skip the 200ms opacity transition so focus is not waiting on a fade.
Accessibility
role="dialog",aria-modal="true",aria-labelledbypointing at the title- Don’t use
role="alertdialog"unless it’s a destructive confirm that needs immediate attention - Backdrop click is optional; never the only way to close
- Return focus even if the trigger unmounted (focus the nearest landmark)
Name the close button. A × with no text is a failure for a screen reader. Prefer visible text (“Close”, “Cancel”) and keep the icon decorative.
The dialog title is the accessible name. Do not rely on aria-label copied from a generic “Dialog” string. If the body has extra context a confirm needs (the file name being deleted), point aria-describedby at that sentence.
Focus order is Header close, Body fields, Footer secondary, Footer primary — unless it is a destructive alertdialog, in which case the safer action (Cancel) is focused first and Delete is the next stop. Say that trade-off. Some teams focus Delete to save a keystroke; that is a product call, not a default.
Keyboard: Escape closes. Enter submits a form if focus is in a text field. Space activates the focused button. Do not close on Enter when the focused control is a textarea.
Security
A modal is a trusted chrome around untrusted or semi-trusted content. Treat it that way.
- If Body renders user HTML (a “preview before delete” card), escape it. The dialog chrome must not become an XSS sink because someone put a title in
dangerouslySetInnerHTML. - A confirm POST needs the same CSRF token as any other mutation. The dialog is not a new origin.
- Do not auto-focus a field that echoes unsanitized query params into the DOM.
- Backdrop is not a security boundary. It hides the page; it does not sandbox it.
inertis UX, not a privilege check.
Edge Cases
- Nested popovers inside a modal (date picker) — they must be in the same focus trap
- Mobile keyboards resizing the viewport
- Don’t destroy content on close if the form should survive a reopen
Those three show up in every strong answer. Add the restore-target-gone case: the trigger was in a row that unmounted (the user deleted the item that opened the dialog). Focus the parent list or the nearest landmark, not document.body if you can help it.
Handling User Edge Cases
| Case | Strategy |
|---|---|
| ❌ Empty confirm / double submit | Disable the primary button while pendingAction === "submit". Ignore a second Enter. |
| ❌ Backdrop click on a destructive dialog | Ignore it. Require an explicit Cancel or Escape so a mis-click does not dismiss. |
| 🔄 User reloads while the modal is open | Controlled open comes from the URL or parent state. A reload without that state stays closed — that is correct. |
| 🔁 Nested date picker | The picker portals into the dialog (or a sibling inside the trap root), not document.body outside inert. |
| 📶 Slow confirm request | Keep the dialog open, show pending on the button, allow Escape to abort via AbortController. |
| ⏳ Trigger unmounted on close | Restore to the nearest landmark or the list that owned the row. Never drop focus into nowhere. |
| 🚫 Focus leaked to the page | Re-run the trap list. If inert is missing, the fallback is aria-hidden on siblings plus the Tab cycle. |
Pro-Level Optimizations
| Area | Suggestion |
|---|---|
| Focus list | Cache tabbables. Refresh with MutationObserver when Body children change, not on every Tab. |
| Backdrop pointer | Close on pointer down on the backdrop only if both down and up landed there. Prevents drag-out closes. |
| Reduced motion | Skip the enter transition so programmatic focus() is not racing a 200ms fade. |
| Keep mounted | Hide with CSS when closed if the form is expensive to remount. Still inert the page only while open. |
| Top layer | Prefer native <dialog>.showModal() for stacking context; keep your own label, scroll lock, and restore. |
| Mobile keyboard | Subscribe to visualViewport resize and pin Footer above the keys so the primary action stays tappable. |
Interview details people skip
A working dialog still fails the follow-ups. These are the ones that come up after “I portal and trap focus.”
Decouple the trigger from the tree. A modal can open from a button, a route, or a background action (session expired). The root owns open / onClose. The trigger does not render the dialog as its child. Compound slots — Modal.Header, Modal.Title, Modal.Close, Modal.Body, Modal.Footer — keep chrome consistent while the parent still controls the boolean.
Track a phase, not just a boolean. closed | opening | open | closing keeps the portal mounted through the exit animation so focus, inert, and the scroll lock stay correct until the last frame. On open you snapshot the trigger, mount, trap, lock, and inert siblings. On close you enter closing, block new input, wait for transitionend, then unlock, un-inert, unmount, and restore focus. If prefers-reduced-motion: reduce matches, duration is zero — do not wait for an event that will never fire.
aria-modal="true" is a name, not a lock. It tells the screen reader the dialog is modal. It does not make the background inert. You still apply real inert (or hide siblings) and you still run the Tab trap. Pair role="dialog" with a label (aria-labelledby on a visible title, or aria-label) and optional aria-describedby. Native <dialog>.showModal() is the production shortcut for top layer + inert + focus; in the interview, implement the pieces so you can name them.
Only the top layer dismisses. Overlay click closes when event.target === event.currentTarget and the dialog is topmost — that is a completed click on the backdrop, not a drag that started on the panel. Escape and the close button go through the same onClose. A second dialog pushes a layerId; the one underneath stays mounted and visible, loses the trap, and gets focus back when the top one pops.
Animate overlay and panel as siblings if they must move independently (dim fades, card slides up). A child cannot transition separately from a parent that is also fading. Size with something like min(600px, calc(100vw - 2rem)) and a viewport-capped height. Header and Footer stay put; Body is the only scroll pane. Restore the previous body.style.overflow on close so a nested or reopened dialog does not leak the lock.
Titles, actions, and copy wrap for longer translations. Inherit dir and use logical CSS. Footer button order follows the design system, not a blanket RTL flip.
Conclusion: How to Design an Accessible Dialog
A modal is a focus product. If Tab leaks to the page behind, or focus vanishes on close, the component is wrong no matter how it looks.
We’ll have walked the pieces interviewers score: a controlled API, a portal to document.body, a Focus Manager that snapshots and restores, a Scroll Lock that compensates the scrollbar, and inert on the app root siblings. The open sequence and the close sequence are the same function in reverse. Confirm, form, and large content share that function and only swap Body and the initial focus target.
Native <dialog> is a valid starting point — say you would use it or Radix / React Aria — and then show you still know the steps the platform does not finish for you. Label the title, keep backdrop click optional, survive a nested picker, and never destroy a form the user is coming back to. That is the senior answer.
