Modal Dialog
UI Coding
Medium
30 min
accessibility
focus-management
portals
design-system
Build a reusable Modal component and use it for a "Delete file?" confirmation.
<Modal open={open} onClose={() => setOpen(false)} title="Delete file?" initialFocusRef={cancelRef}>
…content and buttons…
</Modal>
Requirements
- When
openis false, nothing is rendered. When true, render a dimmed backdrop and a centred dialog intodocument.bodythrough a portal, so parentoverflowandz-indexcan't clip it. - Semantics:
role="dialog",aria-modal="true",aria-labelledby→ the title (rendered as a heading), andaria-describedby→ the body content. - Opening moves focus into the dialog: to
initialFocusRefif given, otherwise to the dialog container itself. - Closing returns focus to whatever was focused before it opened (usually the trigger button).
- Close with <kbd>Escape</kbd>, by clicking the backdrop (but not by clicking inside the dialog), and with a visible close button labelled "Close".
- The page behind doesn't scroll while the modal is open.
- Demo: a "Delete file" button opens the dialog. Cancel closes it. Delete closes it and shows "report.pdf was deleted." For a destructive action, initial focus goes to Cancel.
A full focus trap (<kbd>Tab</kbd> cycling inside the dialog) and making the background inert are the subject of Modal Dialog II. Mention them, but they aren't required here.
Follow-up
- What does the native
<dialog>element withshowModal()give you for free? - Why should a backdrop close on
mousedown/clickon the backdrop itself only? What bug happens when the user drags a text selection out of the dialog? - How would you stack two modals?
Spotted a mistake or a rights concern? Report an issue