How would you design a modal manager system in React?
Create a global modal manager with stacking, portal rendering, focus trapping, ESC handling, and dynamic modal types.
advancedUi patternsreactmodalportalaccessibility
Published: 11/23/2025
Updated: 11/23/2025
Advertisement
đź§© Scenario
You need a global modal manager so any component in the app can open a modal without manually placing modal components everywhere.
Requirements:
- Open any modal from anywhere (context API)
- Support multiple modal types (alert, confirm, custom forms)
- Stack modals (open one over another)
- ESC to close
- Click outside to close
- Focus trap inside modal
- Render via portal to avoid z-index issues
đź§ Answer (Design Overview)
Architecture
- Modal Context + Provider — exposes
openModal(),closeModal(),modals[]. - Portal Rendering — render modals at
document.body. - Stacking Support — treat
modalsas a stack. - Focus Management — trap focus inside the modal, restore focus to opener.
- Escape + Backdrop Close — keyboard + click handling.
- Dynamic Modal Content — render any component passed into
openModal().
Tradeoffs:
- A global manager centralizes behavior but requires careful typing (if using TypeScript).
- Stacked modals complicate focus management.
🎮 Live Demo: Modal Manager System
🔍 Real-World Tips
- Use focus trapping libraries like
focus-trapfor robust accessibility. - Use framer-motion for modal enter/exit animations.
- For complex UIs, allow passing modal-specific
propsto dynamically generated modals. - Maintain a modal registry for different modal types (e.g.,
AlertModal,ConfirmModal,FormModal).
Quick Practice
- Add focus trapping using tab key cycling.
- Add an animation for open/close.
- Add modal types with standardized layouts.
- Persist the last opened modal if the user reloads.
Summary
- A modal manager centralizes modal behavior.
- Use context + portal + modal stack.
- Add focus, ESC, and backdrop handling.
- Scale by registering different modal types.
Frequently Asked Questions
Why use a modal manager instead of local modals?
Local modals don’t scale when multiple features need modals. A central manager standardizes behavior and avoids nested portal issues.
How do you keep accessibility strong?
Use focus trapping, ESC to close, ARIA labels, and restore focus to the trigger element.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement