Overlays

Alert dialog.

Confirm a consequential action with a safe initial focus, pending feedback and retry.

Install the source

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/alert-dialog.json

Registry setup · Examples · API and behavior · Open the playground

COMPLETE EXAMPLES

Use it in context.

Each example includes its imports, data and state. The preview runs that same source. Include the stylesheet once in your application.

Delete a local draft explicitly

Cancel receives focus first. Only the explicit Delete draft action removes the local draft; no service deletion is implied.

Keyboard

  • Opening places focus on Cancel. Tab stays within the modal confirmation.
  • Escape cancels and returns focus. Clicking outside does not dismiss.
  • Delete draft runs the supplied callback and closes after it returns.

States covered

  • Cancel-first focus
  • explicit destructive confirmation
  • synchronous host callback
  • focus restoration
  • local result

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-alert-dialog-delete.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useRef,useState} from 'react';
import {Button,UIProvider} from '@bld8/ui';
import {AlertDialog} from '@bld8/ui/alert-dialog';
export default function DeleteDraftExample(){
  const [deleted,setDeleted]=useState(false),restore=useRef<HTMLButtonElement>(null);
  return <UIProvider><div style={{display:'grid',gap:16,maxWidth:460}}><strong>Release note draft</strong><p>{deleted?'This local draft has been deleted.':'A draft awaiting review.'}</p>
    <AlertDialog trigger={<Button variant="danger" disabled={deleted}>Delete draft</Button>} title="Delete this draft?" description="The local Release note draft will be removed from this example. This action cannot be undone here." confirmLabel="Delete draft" destructive finalFocus={()=>deleted?restore.current:true} onConfirm={()=>setDeleted(true)}/>
    <Button ref={restore} variant="secondary" onClick={()=>setDeleted(false)} disabled={!deleted}>Create another draft</Button><p role="status">{deleted?'Draft deleted locally':'Draft available'}</p>
  </div></UIProvider>;
}

Pending work, cancellation and retry

An abortable local callback fails its first attempt and succeeds on retry. Cancel, Escape, reset and unmount invalidate pending results; hosts own service cancellation and rollback.

Keyboard

  • Cancel stays available during pending work. Escape also cancels the request.
  • A failed attempt keeps the dialog open and moves focus to Retry export.
  • Reset request starts a new confirmation session and aborts its pending callback.

States covered

  • pending
  • duplicate prevention
  • rejected callback
  • retry
  • AbortSignal
  • resetKey
  • noncooperative stale result
  • local sample task

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-alert-dialog-pending-recovery.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useRef,useState} from 'react';
import {Button,Checkbox,UIProvider} from '@bld8/ui';
import {AlertDialog} from '@bld8/ui/alert-dialog';
function pause(signal:AbortSignal,hold:boolean,ignoreAbort:boolean){
  return new Promise<void>((resolve,reject)=>{
    const finish=()=>{signal.removeEventListener('abort',abort);resolve();};
    const timer=hold?undefined:setTimeout(finish,650);
    const abort=()=>{if(ignoreAbort)return;if(timer)clearTimeout(timer);reject(new DOMException('Cancelled','AbortError'));};
    if(signal.aborted)abort();else signal.addEventListener('abort',abort,{once:true});
  });
}
export default function PendingConfirmationExample(){
  const [session,setSession]=useState(0),[hold,setHold]=useState(false),[ignoreAbort,setIgnoreAbort]=useState(false),[requests,setRequests]=useState(0),[cancelled,setCancelled]=useState(0),[result,setResult]=useState('No export prepared'),[open,setOpen]=useState(false);
  const failures=useRef(0);
  return <UIProvider><div style={{display:'grid',gap:16,maxWidth:520}}>
    <AlertDialog trigger={<Button>Prepare export</Button>} open={open} onOpenChange={setOpen} title="Prepare a local export?" description="The first completed sample request fails. Retry uses the same confirmation; Cancel keeps your current data." confirmLabel="Retry export" pendingLabel="Preparing export…" resetKey={session} errorMessage={error=>error instanceof Error?error.message:'Export failed. Try again.'} onConfirm={async({signal})=>{
      setRequests(count=>count+1);try{await pause(signal,hold,ignoreAbort);}catch(error){if(signal.aborted)setCancelled(count=>count+1);throw error;}
      if(signal.aborted)return;
      if(failures.current++===0)throw new Error('The sample export failed. Retry to recover.');
      setResult('Local export prepared');
    }}>{({pending})=><div style={{display:'grid',gap:12}}>
      <Checkbox label="Hold request until cancelled" checked={hold} onCheckedChange={setHold} disabled={pending}/>
      <Checkbox label="Let the sample finish after cancellation" checked={ignoreAbort} onCheckedChange={setIgnoreAbort} disabled={pending||hold}/>
      <Button variant="secondary" onClick={()=>setSession(value=>value+1)}>Reset request</Button>
      <p className="bui-hint">These are local sample tasks. An aborted signal prevents this example from changing its data; a real service must define its own cancellation and transaction rules.</p>
    </div>}</AlertDialog>
    <p role="status" aria-label="Export result">{result}</p><p aria-label="Export request count">Requests: {requests}</p><p aria-label="Export cancellation count">Aborted tasks: {cancelled}</p>
  </div></UIProvider>;
}

Type a target name before confirmation

The host enables confirmation only when the exact project name matches, and resets the typed draft when opening or closing.

Keyboard

  • Cancel receives initial focus; Tab reaches the named confirmation field.
  • The confirmation action stays disabled until ARCHIVE matches exactly.
  • Escape cancels and clears the typed draft through controlled open state.

States covered

  • controlled open
  • host validation
  • disabled confirmation
  • typed target
  • reset on cancel
  • explicit archive

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-alert-dialog-type-confirm.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useState} from 'react';
import {Button,Field,Input,UIProvider} from '@bld8/ui';
import {AlertDialog} from '@bld8/ui/alert-dialog';
export default function TypedConfirmationExample(){
  const [open,setOpen]=useState(false),[typed,setTyped]=useState(''),[archived,setArchived]=useState(false);
  return <UIProvider><div style={{display:'grid',gap:16,maxWidth:480}}>
    <AlertDialog trigger={<Button variant="danger" disabled={archived}>Archive project</Button>} open={open} onOpenChange={next=>{setTyped('');setOpen(next);}} title="Archive project ARCHIVE?" description="Archiving removes this local project from the active list. Type ARCHIVE to enable the explicit archive action." confirmLabel="Archive ARCHIVE" destructive confirmDisabled={typed!=='ARCHIVE'} onConfirm={()=>setArchived(true)}>
      {({pending})=><Field label="Project name" hint="Enter ARCHIVE exactly, including capital letters."><Input value={typed} autoComplete="off" spellCheck={false} disabled={pending} onChange={event=>setTyped(event.target.value)}/></Field>}
    </AlertDialog><p role="status">{archived?'ARCHIVE is archived locally':'ARCHIVE remains active'}</p><Button variant="secondary" disabled={!archived} onClick={()=>setArchived(false)}>Restore project</Button>
  </div></UIProvider>;
}

Confirm leaving an unsaved note

Keep editing preserves the draft. Discard restores the last local save and returns focus to an explicit Open editor action.

Keyboard

  • Leave editor opens only after the note changes; Keep editing receives focus.
  • Escape preserves the draft and returns to Leave editor.
  • Discard changes restores the saved text and focuses Open editor. This example does not intercept browser navigation.

States covered

  • dirty draft
  • safe cancellation
  • explicit discard
  • custom final focus
  • local save
  • host navigation boundary

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-alert-dialog-dirty-exit.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useRef,useState} from 'react';
import {Button,Field,Textarea,UIProvider} from '@bld8/ui';
import {AlertDialog} from '@bld8/ui/alert-dialog';
export default function DirtyExitExample(){
  const [saved,setSaved]=useState('Review before publishing.'),[draft,setDraft]=useState('Review before publishing.'),[editing,setEditing]=useState(true),[status,setStatus]=useState('No unsaved changes');
  const reopen=useRef<HTMLButtonElement>(null),dirty=draft!==saved;
  return <UIProvider><div style={{display:'grid',gap:16,maxWidth:520}}>
    <Field label="Editor note"><Textarea value={draft} disabled={!editing} onChange={event=>{setDraft(event.target.value);setStatus('Draft changed');}}/></Field>
    <div style={{display:'flex',gap:8,flexWrap:'wrap'}}><Button disabled={!editing||!dirty} onClick={()=>{setSaved(draft);setStatus('Note saved locally');}}>Save note</Button>
      <AlertDialog trigger={<Button variant="secondary" disabled={!editing||!dirty}>Leave editor</Button>} title="Discard your unsaved changes?" description="Your current draft differs from the last local save. Keep editing preserves it; Discard changes restores the saved note." confirmLabel="Discard changes" cancelLabel="Keep editing" destructive finalFocus={()=>editing?true:reopen.current} onConfirm={()=>{setDraft(saved);setEditing(false);setStatus('Changes discarded; editor closed');}}/>
      <Button ref={reopen} variant="ghost" onClick={()=>{setEditing(true);setStatus('Editor open');}}>Open editor</Button></div>
    <p role="status">{status}</p><p className="bui-hint">The host decides when navigation needs confirmation. This local example does not install route or browser unload guards.</p>
  </div></UIProvider>;
}

Quick reference

React / TypeScript
<AlertDialog trigger={<Button>Delete draft</Button>} title="Delete this draft?" description="This removes the saved draft." confirmLabel="Delete draft" onConfirm={deleteDraft} />

In the workspace or ZIP starter, import components from @bld8/ui and include @bld8/ui/styles.css once. Registry installations use your local bld8/ source path. Wrap overlays in UIProvider.

API & behaviour

A confirmation uses alertdialog semantics. Cancel receives initial focus; outside presses do not dismiss. Async confirmation prevents duplicate submits, keeps errors available for retry and aborts the local attempt on cancellation. The application remains responsible for server-side authorization and durable transaction guarantees.

AlertDialog

AlertDialog public properties
PropTypeDefault
confirmLabelRequiredstring—
descriptionRequiredReactNode—
titleRequiredstring—
cancelLabelstring | undefined—
childrenReactNode | ((context: AlertDialogRenderContext) => ReactNode)—
classNamestring | undefined—
confirmDisabledboolean | undefinedfalse
defaultOpenboolean | undefinedfalse
destructiveboolean | undefinedfalse
errorMessage((error: unknown) => string) | undefined—
finalFocusboolean | RefObject<HTMLElement | null> | ((closeType: InteractionType) => boolean | HTMLElement | null | void) | undefined—
onCancel(() => void) | undefined—
onConfirm((context: AlertDialogConfirmContext) => void | Promise<void>) | undefined

A successful return closes the dialog. Throw/reject to retain it with retry. Without a callback, Confirm only acknowledges and closes the dialog.

—
onOpenChange((open: boolean) => void) | undefined—
onOpenChangeComplete((open: boolean) => void) | undefined—
openboolean | undefined—
pendingLabelstring | undefined'Working…'
resetKeyunknown

Change when the confirmation target/session changes to abort and reset it.

—
triggerReactElement<unknown, string | JSXElementConstructor<any>> | undefined—

AlertDialogConfirmContext

AlertDialogConfirmContext public properties
PropTypeDefault
attemptRequirednumber

One-based attempt within the current open/reset session.

—
signalRequiredAbortSignal

Aborted on Cancel, Escape, external close, resetKey change or unmount. The host must honour this signal where possible; abort is not server rollback.

—

AlertDialogRenderContext

AlertDialogRenderContext public properties
PropTypeDefault
attemptRequirednumber—
clearErrorRequired() => void—
errorRequiredstring | null—
pendingRequiredboolean—

Tables come from the public TypeScript declarations. Related types and function parameters are shown alongside their component. A dash means no default is declared at the public function boundary.

Related controls

Notes to self

Test this component with real content, keyboard input and both themes. The example is a starting point; labels, error handling and behaviour still need to fit the application.