Modal Dialog examples
Ek accessible modal jo native dialog element par bana hai, backdrop, focus trapping, aur Escape se close hone ki functionality ke sath.
Ek modal dialog jo browser ke native dialog element par bana hai, jis se focus trapping, backdrop rendering, aur Escape-to-close khud ba khud milte hain bajaye is ke ke aap ko JavaScript khud maintain karni paray.
Is mein backdrop click to dismiss, sahi ARIA labelling, aur ek React wrapper shamil hai jo open prop ko element ke apne methods ke sath sync karta hai.
Confirmation modal dialog
Two actions with the destructive one in red and placed last. The button names the action, so it reads correctly on its own.
"use client";
import { useRef } from "react";
export default function ConfirmDialog() {
const ref = useRef<HTMLDialogElement>(null);
return (
<>
<button
type="button"
onClick={() => ref.current?.showModal()}
className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
>
Delete project
</button>
<dialog
ref={ref}
onClick={(e) => {
if (e.target === ref.current) ref.current?.close();
}}
aria-labelledby="dialog-title"
aria-describedby="dialog-description"
className="m-auto w-full max-w-md rounded-xl p-0 backdrop:bg-gray-900/50"
>
<div className="p-6">
<h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Delete this project?</h2>
<p id="dialog-description" className="mt-2 text-sm text-gray-600">
This removes the project and all of its files. This action cannot be undone.
</p>
<div className="mt-6 flex justify-end gap-3">
<button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
<button type="button" onClick={() => ref.current?.close()} className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-500">Delete project</button>
</div>
</div>
</dialog>
</>
);
}Modal dialog with a form
A single-field form using method=dialog, so submitting closes the dialog and reports the clicked button's value without extra wiring.
"use client";
import { useRef } from "react";
export default function RenameDialog() {
const ref = useRef<HTMLDialogElement>(null);
return (
<>
<button
type="button"
onClick={() => ref.current?.showModal()}
className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
>
Rename project
</button>
<dialog
ref={ref}
onClick={(e) => {
if (e.target === ref.current) ref.current?.close();
}}
aria-labelledby="dialog-title"
aria-describedby="dialog-description"
className="m-auto w-full max-w-md rounded-xl p-0 backdrop:bg-gray-900/50"
>
<form method="dialog" className="p-6">
<h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Rename project</h2>
<p id="dialog-description" className="mt-2 text-sm text-gray-600">Choose a name your team will recognize.</p>
<label htmlFor="project-name" className="mt-4 block text-sm font-medium text-gray-900">Project name</label>
<input id="project-name" name="name" type="text" required autoComplete="off" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />
<div className="mt-6 flex justify-end gap-3">
<button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
<button type="submit" className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Save name</button>
</div>
</form>
</dialog>
</>
);
}Bottom sheet modal on mobile
Pinned to the bottom edge with a drag-handle cue below the sm breakpoint, and a centered dialog above it.
"use client";
import { useRef } from "react";
export default function ShareSheet() {
const ref = useRef<HTMLDialogElement>(null);
return (
<>
<button
type="button"
onClick={() => ref.current?.showModal()}
className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
>
Share
</button>
<dialog
ref={ref}
onClick={(e) => {
if (e.target === ref.current) ref.current?.close();
}}
aria-labelledby="dialog-title"
aria-describedby="dialog-description"
className="m-0 mt-auto w-full max-w-none rounded-b-none rounded-t-2xl p-0 backdrop:bg-gray-900/50 sm:m-auto sm:max-w-md sm:rounded-xl"
>
<div className="p-6">
<div className="mx-auto mb-4 h-1.5 w-10 rounded-full bg-gray-300 sm:hidden" aria-hidden="true"></div>
<h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Share this page</h2>
<p id="dialog-description" className="mt-1 text-sm text-gray-600">Anyone with the link can view it.</p>
<ul className="mt-4 space-y-1">
<li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Copy link</button></li>
<li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Send by email</button></li>
<li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Open in a new tab</button></li>
</ul>
<button type="button" onClick={() => ref.current?.close()} className="mt-4 w-full rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
</div>
</dialog>
</>
);
}Side drawer modal
A full-height panel on the right for filters or settings. Still a native modal dialog, so focus trapping and Escape work the same way.
"use client";
import { useRef } from "react";
export default function FilterDrawer() {
const ref = useRef<HTMLDialogElement>(null);
return (
<>
<button
type="button"
onClick={() => ref.current?.showModal()}
className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
>
Open filters
</button>
<dialog
ref={ref}
onClick={(e) => {
if (e.target === ref.current) ref.current?.close();
}}
aria-labelledby="dialog-title"
className="m-0 ml-auto h-screen max-h-none w-full max-w-sm rounded-none p-0 backdrop:bg-gray-900/50"
>
<div className="flex h-full flex-col">
<div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
<h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Filters</h2>
<button type="button" onClick={() => ref.current?.close()} aria-label="Close filters" className="rounded-md p-2 text-gray-500 hover:bg-gray-100">
<svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
</button>
</div>
<div className="flex-1 overflow-y-auto px-6 py-5">
<fieldset>
<legend className="text-sm font-medium text-gray-900">Category</legend>
<div className="mt-3 space-y-2 text-sm text-gray-700">
<label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Design</label>
<label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Engineering</label>
<label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Marketing</label>
</div>
</fieldset>
</div>
<div className="flex gap-3 border-t border-gray-200 px-6 py-4">
<button type="button" onClick={() => ref.current?.close()} className="flex-1 rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Clear</button>
<button type="button" onClick={() => ref.current?.close()} className="flex-1 rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Show results</button>
</div>
</div>
</dialog>
</>
);
}Scrollable modal with sticky header and footer
Long content scrolls inside the panel while the title and actions stay visible. Uses open:flex so the closed dialog stays hidden.
"use client";
import { useRef } from "react";
export default function TermsDialog() {
const ref = useRef<HTMLDialogElement>(null);
return (
<>
<button
type="button"
onClick={() => ref.current?.showModal()}
className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
>
Review terms
</button>
<dialog
ref={ref}
onClick={(e) => {
if (e.target === ref.current) ref.current?.close();
}}
aria-labelledby="dialog-title"
className="m-auto max-h-[80vh] w-full max-w-lg flex-col rounded-xl p-0 backdrop:bg-gray-900/50 open:flex"
>
<div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
<h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Terms of service</h2>
<button type="button" onClick={() => ref.current?.close()} aria-label="Close terms" className="rounded-md p-2 text-gray-500 hover:bg-gray-100">
<svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
</button>
</div>
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-6 py-4 text-sm text-gray-600">
<p>Section 1. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
<p>Section 2. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
<p>Section 3. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
<p>Section 4. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
<p>Section 5. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
<p>Section 6. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
</div>
<div className="flex justify-end gap-3 border-t border-gray-200 px-6 py-4">
<button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Decline</button>
<button type="button" onClick={() => ref.current?.close()} className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Accept</button>
</div>
</dialog>
</>
);
}What is a Modal Dialog?
Modal dialog ek aisa panel hai jo page ke upar khulta hai aur us waqt tak peeche ki har cheez ke sath interaction block kar deta hai jab tak usay handle na kiya jaye. Block karne wala hissa hi iska asal maqsad hai: yeh un lamhat ke liye hota hai jahan kisi faislay ke baghair agay barhna ghalat ho, jaisay kisi deletion ko confirm karna ya koi zaroori step mukammal karna. Jo cheez interrupt karna zaroori na samjhe, usay page, panel, ya toast hona chahiye.
Modals ko theek tarah se banana mushkil kaam hai, ishi wajah se inke liye itni sari libraries mojood hain. Jo cheezein theek honi chahiye un ki list lambi hai: jab modal khule toh focus dialog ke andar jana chahiye aur band hone par wapas trigger par aana chahiye, tabbing panel ke andar hi ghoorni chahiye bajaye peeche page par jane ke, peeche wala page scroll nahi hona chahiye, Escape key se yeh band hona chahiye, dialog ek naam aur role ke sath announce hona chahiye, aur jab yeh khula ho toh niche ki tamam cheezein assistive technology se chupai hui honi chahiye.
Native dialog element ab in mein se taqreeban sab kuch khud handle kar leta hai. Is par showModal call karne se focus trap ho jata hai, ek backdrop pseudo-element render ho jata hai, baqi document inert ho jata hai, aur Escape key close karne ke liye wire ho jati hai - aisa behaviour jiske liye pehle kuch so lineon ki careful JavaScript chahiye hoti thi. Browser support 2022 se kafi behtareen hai, jis ki wajah se naye kaam ke liye khud banaye gaye version ko justify karna mushkil hai.
Platform aap ko jo cheez nahi deta woh backdrop click to dismiss hai, kyunke backdrop ek pseudo-element hai na ke koi aisa node jis par aap listener laga sakein. Iska hal yeh hai ke dialog par hi clicks listen kiye jayein aur yeh check kiya jaye ke click ka target dialog khud hai ya uske andar ki koi cheez - agar click seedha dialog element par hua hai toh iska matlab hai ke woh panel ke baahir padding area se aaya hai, jo user ke liye backdrop hi hai.
Anatomy
- Trigger
- Woh button jo dialog ko kholta hai. Close hone par focus khud ba khud yahan wapas aa jata hai, ishi wajah se trigger koi div handler wala hone ke bajaye ek asli button hona chahiye.
- Dialog element
- Native dialog. Is mein width constraint aur backdrop styling hoti hai, aur padding zero par set hoti hai taake andar ka container spacing ko control kar sakay.
- Backdrop
- Alag element ke bajaye backdrop pseudo-class ke zariye style hota hai. Yeh sirf tab mojood hota hai jab dialog showModal ke sath khola jaye.
- Title
- Dialog ka accessible naam, jo aria-labelledby ke sath connected hota hai. Isay category label ke tor par nahi, balkay ek sawal ya task ke tor par likhein.
- Description
- Optional supporting text jo aria-describedby ke sath connected hota hai. Dangerous actions ke liye, yeh woh jagah hai jahan unka natija bataya jata hai.
- Action row
- Footer buttons, jo right-aligned hote hain aur primary ya destructive action sab se aakhir mein hota hai taake woh angoothe (thumb) aur aankh ke end point ke sab se qareeb ho.
How to Use
- 1
Copy the markup
Static page ke liye HTML version lein ya component tree ke liye React wrapper. Dono andar se same native element use karte hain.
- 2
Open it with showModal
show ke bajaye showModal call karein. Sadha show method dialog ko bina backdrop, bina focus trapping, aur baqi page ko inert kiye baghair kholta hai.
- 3
Close paths wire karein
Escape ko browser khud handle karta hai. Ek close button aur backdrop click handler add karein taake bahar jane ke teen tareeqe hon, aur un sab ko onClose ke zariye route karein.
- 4
Dialog ko label dein
aria-labelledby ko title ke id par point karein, aur agar description ho toh aria-describedby ko us par. Naam ke baghair dialog unlabeled dialog ke tor par announce hota hai.
- 5
Panel ko style dein
Padding dialog par lagane ke bajaye andar wale container par dein, taake backdrop click check reliable rahe - dialog par padding uske apne click area ka hissa ban jati hai.
Features
Native focus trapping
Open hone par focus dialog ke andar jata hai aur ussi mein cycle hota hai, jise browser handle karta hai bajaye iske ke aapko koi keydown listener theek rakhna pare.
Focus trigger par wapas jata hai
Close hone par, focus automatically us element par wapas jata jisne dialog khola tha, taake keyboard user wahi se shuru kare jahan usne chora tha.
Bina kisi extra element ke backdrop
Backdrop ek pseudo-element hai jo backdrop variant se styled hota hai, isliye koi alag overlay div position, stack, ya sync mein rakhne ki zarurat nahi parti.
Escape isay close kar deta hai
Element ke andar built-in hai. React wrapper aane wale close event ko sunta hai taake jab browser khud dialog close kare toh open prop sync mein rahe.
Page ka baqi hissa inert ho jata hai
Modal dialog ke peechay ka content focusable nahi hota aur assistive technology se chupa rehta hai, bina kisi cheez par khud aria-hidden set kiye.
Dismiss karne ke liye backdrop click
Ek click target check padding area ko panel contents se alag karta hai, aur bina kisi extra overlay node ke woh dismiss behaviour deta hai jo log expect karte hain.
Common Uses
Destructive action ko confirm karna
Account, project, ya file delete karna - aisi situations jahan galti se click hone ke nateeje aese hon jinhein toast ke zariye undo na kiya ja sake.
Chote forms
Kisi item ka naam badalna, teammate ko invite karna, ya single value enter karna, jahan kisi ko alag page par bhejne se unki jagah kho jati.
Zaruri onboarding steps
Woh step jo aage barhne se pehle lazmi mukammal hona chahiye, jese updated terms accept karna ya workspace select karna.
Media aur detail views
Current page ke upar bari image ya record ki details dikhana, jahan same scroll position par wapas aana matter karta hai.
Accessibility
- Dialog element ke paas implicit dialog role hota hai, aur showModal ke sath kholne par implicit modal state hoti hai, isliye manually koi role ya aria-modal attribute add karne ki zarurat nahi.
- aria-labelledby title par point karta hai taake dialog generic dialog ki bajaye naam ke sath announce ho.
- aria-describedby supporting text par point karta hai taake destructive action ka nateeja skip hone ke bajaye parha jaye.
- Open hone par focus dialog ke andar jata hai aur close hone par trigger par wapas aata hai, yeh dono cheezein browser handle karta hai.
- Jab tak dialog khula hai, iske bahar ki har cheez inert hoti hai, taake tabbing iske peechay wale page tak na pahunch sake aur screen readers iske zariye na parhein.
- Escape by default dialog ko close kar deta hai. Isay mat rokein; agar koi dialog dismiss nahi hona chahiye, toh masla yeh hai ke interaction modal nahi honi chahiye.
- Close button ko visible label ya aria-label chahiye. Baghair accessible name ke sirf icon wala close button sab se common dialog defects mein se ek hai.
Customization
- Backdrop ko backdrop variant se style dein - halka karne ke liye backdrop:bg-gray-900/50, aur agar peechay ka page soft karna ho toh backdrop:backdrop-blur-sm.
- Padding dialog element par lagane ke bajaye andar wale container par rakhein, warna padding dialog ke click area ka hissa ban jati hai aur backdrop dismiss predictablly kaam karna chor deta hai.
- Small screens par isay bottom edge par pin karke aur sm se upar centered positioning restore karke bottom sheet bana dein.
- Open state par starting-style rule ke sath entrance ko animate karein. Isay 200ms se kam rakhein; slow modal unresponsive lagta hai kyunki content tab tak parha nahi ja sakta jab tak woh settle na ho.
- Bare dialog ke liye, max-width change karein. max-w-2xl ke baad, yeh sochein ke kya content ko ek page hona chahiye - lambay modals buri tarah scroll hote hain aur apne actions chupa lete hain.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| open * | boolean | - | Yeh check karne ke liye ke dialog show ho raha hai ya nahi. Component isay conditionally render karne ke bajaye native showModal aur close methods ke sath sync karta hai. |
| onClose * | () => void | - | Tab call hota hai jab dialog kisi bhi tareeqey se close ho - Escape key, backdrop click, ya close button se. Isay open ko wapas false set karne ke liye use karein. |
| title * | string | - | Dialog ka accessible naam, jo aria-labelledby ke zariye connect hota hai. Isay kabhi mat chhodein; bina naam ke dialog ko sirf ek dialog announce kiya jata hai. |
| description | string | - | Optional supporting text, jo aria-describedby ke zariye connect hota hai taake yeh title ke baad parha jaye na ke skip ho. |
| children | ReactNode | - | Dialog ki body aur actions. Actions ko sab se aakhir mein rakhein taake tab order un tak pohnchne se pehle baqi content se guzre. |
Why Use These Modal Dialogs?
Yeh khud se dobara banane ke bajaye platform ko use karta hai. Focus trapping, inert background, aur Escape handling woh cheezein hain jo khud banaye gaye modals mein ghalat ho jati hain, aur yahan yeh aapki nahi balkay browser ki zimdari hain.
Iska matlab yeh bhi hai ke koi dependency nahi hai. Ek headless dialog library ek behtar choice ho sakti hai, lekin confirmation prompt ke liye iska matlab ek package ship karna, uska version track karna, aur uski API seekhna hai taake woh behaviour mil sakay jo element pehle se provide karta hai.
React wrapper element ki apni state ke sath sync hota hai na ke isay conditionally render karta hai, toh Escape se band hone wala dialog bhi onClose fire karta hai aur open prop screen par mojood cheez se out of sync nahi hota.
Tips
- showModal use karein, kabhi show nahi. Farq modal behaviours ke pure set ka hai - show ke sath aapko sirf ek panel milta hai jo upar hota hai aur kuch nahi.
- Padding inner container par set karein, dialog par nahi, warna backdrop click check un clicks par bhi chal paray ga jo panel ka hissa lagte hain.
- Button mein action ka naam dein. Delete project akele mein parha ja sakta hai; Confirm ke liye title parhna parta hai, jo screen reader use karne walay ke focus mein shayad na ho.
- Modals ko nest mat karein. Agar kisi dialog ko doosra dialog kholna paray, toh doosri layer lagane ke bajaye flow ko dobara sochne ki zaroorat hai.
- Current browsers mein showModal se body scroll pehle hi lock ho jati hai, isliye iske upar overflow-hidden class lagane se layout shift ho sakta hai kyunke scrollbar do baar gayab hota hai.
- Sirf keyboard se test karein: kholein, har control par tab karein, Escape press karein. Agar focus trigger ke ilawa kisi aur jagah chala jaye, toh koi cheez dialog ko sync karne ke bajaye conditionally render kar rahi hai.