Modal Dialog — Front-End System Design for an Overlay Window Component
A deep dive into designing a robust, accessible modal dialog — from focus trapping and body scroll lock to declarative and imperative APIs.
system designmodal dialogoverlayaccessibility
1. Requirements & Scoping
A modal dialog seems like a simple box that pops up over the page. But behind that box sits a surprising amount of complexity: focus management, scroll locking, animation lifecycle, stacking order, and screen-reader announcements. Get any of these wrong and the component becomes either annoying or unusable.
Before we write code, we scope what this modal must actually do. The goal is a reusable overlay that works for alerts, confirmations, forms, and panels without every parent component reinventing the wheel.
Key Insight
The hardest part of a modal is not the visual overlay — it is managing the boundary between the dialog and the rest of the page. Keyboard, screen reader, and scroll behavior all need to be contained.
Functional
Display content above the current page
Open via declarative props or imperative trigger
Close via Escape key, overlay click, or close button
Trap focus while open and restore focus on close
Lock body scroll and prevent background interaction
Support stacked dialogs with only the top one interactive
Non-Functional
Accessibility: WCAG 2.1 AA, full keyboard + screen-reader support
Performance: no layout thrash, only transform/opacity animations
Bundle: component tree under 4KB gzipped
Resilience: reduced-motion support, graceful SSR fallback
Start with the non-functional requirements. A modal that is not accessible or that thrashes the main thread is worse than no modal at all.
2. Component Architecture & API
I split the modal into a small family of components. The provider owns the registry and stacking order, the trigger opens the dialog, and the portal teleports the markup to the document body so it escapes any local stacking contexts.
Why a portal? Because a modal inside a deeply nested component can be clipped by a parent with overflow: hidden or buried under a sibling with a higher z-index. Rendering at document.body puts the overlay in the same stacking context as the page root, so it always wins.
example.ts
Note
The initialFocusRef and returnFocusRef props give consumers control without forcing them to manage focus manually. By default we focus the first focusable element and return focus to the trigger.
The ModalContent is the focus container. It registers itself with the focus trap, handles the Escape key, and exposes the accessible dialog role. The overlay is a separate element so we can capture clicks on the backdrop without accidentally closing when the user clicks inside the dialog.
3. Data Model & State Shape
A modal has two kinds of state: visible state and lifecycle state. The visible state answers "is it open?" The lifecycle state answers "is it entering, fully open, or leaving?" You need both because we cannot unmount the dialog the moment isOpen becomesfalse — the exit animation needs time to finish.
I also keep a registry of all active dialogs. This lets us support stacking: when multiple modals are open, only the top one should respond to Escape and trap focus. The rest stay mounted but become inert.
example.ts
Tip
Never derive animation state from isOpen alone. Keep a separate animationPhase so the component can remain mounted during the closing transition and then unmount cleanly at the end.
4. Interface Definition (API)
A modal is almost entirely a client-side component, so the API design is about how the component talks to its parent and how the user talks to it. I offer two consumption patterns: declarative, where the parent owns the boolean; and imperative, where a ref exposes open andclose.
Component API
The callback API is intentionally narrow. The parent only needs to know when the dialog requests to close — the actual open/close decision stays with the parent. This makes it easy to add async validation before closing, such as "are you sure?" prompts.
example.tsx
Imperative Handle
Imperative handles are useful when the trigger is far from the state. For example, a global confirmation dialog in an SDK can be opened from anywhere without prop drilling. We expose a minimal surface: open, close, and focus.
example.tsx
Key Insight
In an interview, mention that you prefer declarative APIs but keep imperative APIs for cross-cutting concerns like global confirmation dialogs. It shows you understand when each pattern shines.
5. Component Deep Dive
Let's walk through the implementation piece by piece. The two hardest problems are focus trapping and body scroll locking. Everything else is decorating those behaviors.
Focus Trap
When the dialog opens, focus moves to the first focusable element. While the dialog is open, pressing Tab should cycle within the dialog, not leak to the page. When the dialog closes, focus returns to the element that opened it. This is not optional for accessibility — it is required by the dialog pattern.
example.ts
Warning
A common bug: only handling Tab and not Shift+Tab. The reverse cycle must wrap from the first element back to the last. Test both directions with a keyboard.
Body Scroll Lock
A modal blocks interaction with the page, so the page should not scroll behind it. The naive approach is to setoverflow: hidden on body, but that causes a layout shift when the scrollbar disappears. We compensate by adding padding equal to the scrollbar width.
example.ts
Styling & Animation
The overlay and content animate independently. We fade the overlay and scale/translate the content. Both use transform or opacity, so the GPU handles the animation. We also respect prefers-reduced-motion by disabling transitions for users who need it.
example.css
Tip
Always set max-width relative to the viewport and max-height relative to the dynamic viewport. A dialog that overflows on mobile is a broken dialog.
6. Data Flow & Interaction
The interaction flow is a small state machine. The user triggers an open, the dialog enters an opening animation, becomes fully open, waits for a close intent, enters a closing animation, and finally unmounts. Throughout this, we manage focus, body scroll, and the dialog stack.
Modal state transitions — closed, opening, open, closing, and returning focus
Focus Management Flow
When the dialog opens, we save the previously focused element, move focus into the dialog, and start trapping. When the dialog closes, we stop the trap and restore focus. If the previously focused element no longer exists, we fall back to the trigger or the body.
Focus management — save trigger focus, trap inside dialog, restore on close
Note
Focus restoration is especially important for screen-reader users. If focus is dropped on close, the user lands at the top of the document and has to navigate back down from scratch.
7. Performance Optimization
A modal is a blocking overlay, so any jank during open or close is immediately noticeable. The key is to keep all animation work off the main thread and avoid DOM thrashing.
GPU-Composited Animations
We animate opacity on the overlay and transform on the content. Both are composite-only properties. We never animatewidth, height, top, or left, which would trigger layout and paint.
Lazy Mount & Unmount
Rather than keeping every dialog in the DOM forever, we mount the portal only when the dialog is opening or open. After the closing animation ends, we unmount. This keeps the DOM light and avoids hidden focusable elements cluttering the page.
Layer Isolation
The portal renders the overlay with a high z-index and isolation: isolate on the content. This creates a new stacking context and prevents any rogue z-index from a parent component from leaking above the modal.
The holy trinity of modal performance: portal to body, animate only opacity/transform, and unmount after exit. Do those three things and the modal will feel native even on low-end devices.
8. Security Considerations
A dialog often displays sensitive content — confirmations, forms, payment details. We must make sure the overlay cannot be bypassed and that the content does not introduce injection vulnerabilities.
Clickjacking Protection
The overlay click-to-close handler must verify the target is the overlay itself, not a child. If a malicious or buggy child element spans the full dialog, a click on it could otherwise close the modal unexpectedly. We use e.target === e.currentTarget to guard this.
Content Sanitization
If the modal renders user-generated HTML, sanitize it before injection. Use DOMPurify or a trusted HTML sanitizer. Never pass raw user input into dangerouslySetInnerHTML without validation.
Stacking Context Boundaries
Because the modal is portaled to document.body, it shares the global stacking context. We set a high z-index and never let consumers override it. If a consumer needs a custom z-index, they should use a separate root-level portal, not tweak the modal component.
Warning
Never allow arbitrary dangerouslySetInnerHTML in modal content. A dialog is a trusted surface, and XSS inside a modal can trick users into confirming destructive actions.
9. Testing Strategy
A modal is one of the most accessibility-critical components in an application, so its tests should cover keyboard, screen reader, and focus behavior as thoroughly as rendering.
Component Tests
We use @testing-library with user-event to simulate real keyboard behavior. Tests verify focus trapping, Escape close, overlay click, and focus restoration. These are the behaviors that break silently when someone refactors the hook.
example.ts
Visual Regression Tests
Dialogs are prone to visual regressions: broken centering, clipped content, or the overlay disappearing. We capture screenshots in multiple viewports and at the open and closed states.
Accessibility Tests
We run axe-core on the open dialog and verify that the dialog has role="dialog", an accessible name viaaria-labelledby, and aria-modal="true". Keyboard tests also cover the reverse tab cycle.
Tip
The most important test: open the modal, press Tab until you wrap, press Shift+Tab until you wrap back, press Escape, and confirm focus is where it started. If that passes, most accessibility issues are covered.
10. Accessibility
Accessibility is not a layer you add at the end — it is the foundation of a good modal. A dialog that fails accessibility breaks the experience for keyboard users, screen-reader users, and anyone relying on predictable focus behavior.
ARIA Roles: The root element uses role="dialog" with aria-modal="true". The title is linked via aria-labelledbyand the description via aria-describedby.
Keyboard Navigation:Tab and Shift+Tab cycle within the dialog. Escape closes unless the consumer disables it.Enter and Space activate the focused action.
Screen Readers: When the dialog opens, the accessible name is announced. We keep the rest of the page inert by usingaria-hidden on siblings or by using the native dialog element when possible.
Color Contrast: The overlay is translucent dark, and the content panel uses surface colors that pass WCAG AA contrast against their backgrounds.
Reduced Motion: Transitions are disabled when prefers-reduced-motion: reduce is active. The dialog still opens and closes instantly, but without animation.
Tip
Test your modal with a screen reader and your eyes closed. If you can open, read, act, and close the dialog without seeing the screen, the accessibility is in good shape.
Live Demo
Here's the modal dialog running live. Open it, tab through the controls, try Escape, and click the overlay. Notice how focus is managed and how the background is locked.
Keyboard shortcut: press Enter on the trigger, then Tab to cycle, Shift+Tab to reverse, and Escape to close.