Dialog
A headless modal and non-modal dialog component that provides accessibility features and focus management.
Live Demo
function DialogDemo() { const [open, setOpen] = React.useState(false); return ( <div className='dialog-demo-container'> <Dialog.Root className='dialog' open={open} onOpenChange={setOpen}> <Dialog.Trigger className='dialog-trigger'> Open Dialog </Dialog.Trigger> <Dialog.Overlay className='dialog-overlay'/> <Dialog.Content className='dialog-content'> <Dialog.Title className='dialog-title'> Dialog Title </Dialog.Title> <Dialog.Description className='dialog-description'> If you delete this item, it will be permanently removed. Are you sure you want to delete it? </Dialog.Description> <div className='dialog-actions'> <Dialog.Close className='dialog-close'> Close </Dialog.Close> <Button className='dialog-continue'> Continue </Button> </div> </Dialog.Content> </Dialog.Root> </div> ); }
The live demo presents a common confirmation dialog pattern with title, description, dismiss action, and primary action.
Features
- ✅ Modal and non-modal dialog support
- ✅ Controlled and uncontrolled state management
- ✅ Focus trapping and restoration
- ✅ Click outside to close
- ✅ Automatic portal rendering to document.body
- ✅ Polymorphic components with
asprop - ✅ Custom focus management with initial and final focus
- ✅ Force mount for animation libraries
Import
import { Dialog } from '@turkish-technology/spar';
Anatomy
The Dialog component is built as a compound component with multiple parts:
Structure
<Dialog.Root>
<Dialog.Trigger />
<Dialog.Overlay />
<Dialog.Content>
<Dialog.Title />
<Dialog.Description />
<Dialog.Close />
</Dialog.Content>
</Dialog.Root>
Data Flow:
Dialog.Rootmanages open/close state and provides context to all child componentsDialog.Triggertoggles the dialog state and maintains focus referenceDialog.Overlayprovides background overlay with click-outside-to-close behavior (portals todocument.bodyby default)Dialog.Contenthandles focus management and keyboard interactions (portals todocument.bodyby default)Dialog.TitleandDialog.Descriptionprovide accessible labelingDialog.Closeprovides a way to close the dialog from within the content
Code Examples
Controlled State Management
Control the dialog's open state externally for integration with other components or form validation.
function ControlledDialog() {
const [open, setOpen] = React.useState(false);
const handleSave = () => {
// Perform save operation
console.log('Saving...');
setOpen(false);
};
return (
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Trigger>Edit Profile</Dialog.Trigger>
<Dialog.Overlay />
<Dialog.Content>
<Dialog.Title>Edit Profile</Dialog.Title>
<Dialog.Description>
Make changes to your profile here.
</Dialog.Description>
<div>
<button onClick={handleSave}>Save Changes</button>
<Dialog.Close>Cancel</Dialog.Close>
</div>
</Dialog.Content>
</Dialog.Root>
);
}
Uncontrolled with Default State
Use uncontrolled mode when you don't need to manage the dialog state externally.
function UncontrolledDialog() {
return (
<Dialog.Root defaultOpen={false}>
<Dialog.Trigger>Open Settings</Dialog.Trigger>
<Dialog.Overlay />
<Dialog.Content>
<Dialog.Title>Settings</Dialog.Title>
<Dialog.Description>
Configure your application settings.
</Dialog.Description>
<Dialog.Close>Done</Dialog.Close>
</Dialog.Content>
</Dialog.Root>
);
}
Non-Modal Dialog
Create non-modal dialogs that don't block interaction with the underlying page.
function NonModalDialog() {
return (
<Dialog.Root modal={false}>
<Dialog.Trigger>Open Info Panel</Dialog.Trigger>
<Dialog.Content
role="dialog"
onEscapeKeyDown={e => {
// Custom escape handling for non-modal
console.log('Escape pressed in non-modal dialog');
}}
>
<Dialog.Title>Information Panel</Dialog.Title>
<Dialog.Description>
This is a non-modal dialog. You can still interact with the page
behind it.
</Dialog.Description>
<Dialog.Close>Close Panel</Dialog.Close>
</Dialog.Content>
</Dialog.Root>
);
}
Custom Focus Management
Control initial focus and focus restoration for optimal user experience.
function CustomFocusDialog() {
const [open, setOpen] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement>(null);
return (
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Trigger>Create Account</Dialog.Trigger>
<Dialog.Overlay />
<Dialog.Content
initialFocus={() => inputRef.current!}
onOpenAutoFocus={event => {
// Custom logic before auto-focus
console.log('Dialog is about to focus');
}}
onCloseAutoFocus={event => {
// Custom logic before focus restoration
console.log('Dialog is about to restore focus');
}}
>
<Dialog.Title>Create New Account</Dialog.Title>
<Dialog.Description>
Enter your details to create an account.
</Dialog.Description>
<div>
<label>
Username:
<input ref={inputRef} type="text" />
</label>
</div>
<div>
<button type="submit">Create</button>
<Dialog.Close>Cancel</Dialog.Close>
</div>
</Dialog.Content>
</Dialog.Root>
);
}
Polymorphic Components
Use the as prop to render dialog parts as different HTML elements or custom
components.
function PolymorphicDialog() {
return (
<Dialog.Root>
<Dialog.Trigger as="div" role="button" tabIndex={0}>
Custom Trigger Element
</Dialog.Trigger>
<Dialog.Overlay as="section" />
<Dialog.Content>
<Dialog.Title as="h1" level={1}>
Main Dialog Title
</Dialog.Title>
<Dialog.Description as="div">
Custom description container
</Dialog.Description>
<Dialog.Close as="span" role="button" tabIndex={0}>
Custom Close Element
</Dialog.Close>
</Dialog.Content>
</Dialog.Root>
);
}
Animation Support
Use forceMount on the root for animation libraries that need to control
mounting and unmounting.
function AnimatedDialog() {
const [open, setOpen] = React.useState(false);
return (
<Dialog.Root open={open} onOpenChange={setOpen} forceMount>
<Dialog.Trigger>Open Animated Dialog</Dialog.Trigger>
<Dialog.Overlay
style={{
opacity: open ? 1 : 0,
transition: 'opacity 0.2s ease',
}}
/>
<Dialog.Content
style={{
transform: open ? 'scale(1)' : 'scale(0.95)',
opacity: open ? 1 : 0,
transition: 'all 0.2s ease',
}}
>
<Dialog.Title>Animated Dialog</Dialog.Title>
<Dialog.Description>
This dialog has custom animations.
</Dialog.Description>
<Dialog.Close>Close</Dialog.Close>
</Dialog.Content>
</Dialog.Root>
);
}
API Reference
Dialog / Dialog.Root
The root container that manages dialog state and provides context to all child
components. Dialog and Dialog.Root are the same component - the difference
is only import/notation style.
Props
| Name | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | - | Dialog trigger, overlay, and content components |
id? | string | auto-generated | Custom base ID for ARIA relationships; sub-IDs are derived as ${id}-title, ${id}-description, ${id}-content |
open? | boolean | undefined | Controlled open state |
onOpenChange? | (open: boolean) => void | undefined | Callback when open state changes |
defaultOpen? | boolean | false | Initial open state for uncontrolled usage |
modal? | boolean | true | Whether dialog is modal (blocks interaction outside) |
disabled? | boolean | false | Disables all dialog triggers (prevents opening) |
forceMount? | boolean | false | Always render portal/overlay/content for animation libraries |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
onOpenChange | (open: boolean) | Open state changes | User interaction or programmatic change |
Dialog.Trigger
Interactive element that opens the dialog when activated. Extends all Button
component props including polymorphic rendering via the as prop.
Props
| Name | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | ((state: DialogTriggerRenderProps) => React.ReactNode) | - | Trigger content or render props function |
disabled? | boolean | false | Disables trigger interaction |
autoFocus? | boolean | false | Whether the button should receive focus on mount |
isLoading? | boolean | false | Loading state with screen reader support |
isPressed? | boolean | undefined | Toggle state - creates a toggle button when defined |
onPressedChange? | (pressed: boolean) => void | undefined | Callback fired when toggle state changes |
ref? | React.Ref<HTMLElement> | undefined | Ref forwarded to trigger element |
...props | ButtonProps | - | All standard Button component attributes |
Render Props (DialogTriggerRenderProps)
| Property | Type | Description |
|---|---|---|
isOpen | boolean | Whether the dialog is currently visible |
disabled | boolean | Whether the trigger is disabled |
open | () => void | Function to programmatically open the dialog (no-op while disabled) |
close | () => void | Function to programmatically close the dialog |
toggle | () => void | Function to programmatically toggle the dialog (no-op while disabled) |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
onClick | (event: React.MouseEvent) | Trigger clicked | Mouse click |
onKeyDown | (event: React.KeyboardEvent) | Key pressed on trigger | Keyboard interaction |
HTML Attributes
| Attribute | Value | Purpose |
|---|---|---|
data-state | "open" | "closed" | Current dialog state |
data-disabled | "" | Present when disabled |
data-loading | "" | Present when loading |
data-pressed | "" | Present when toggle button is active |
data-autofocus | "" | Present when autoFocus is true |
Dialog.Overlay
Background overlay that appears behind dialog content and handles click-outside behavior.
Props
| Name | Type | Default | Description |
|---|---|---|---|
children? | React.ReactNode | undefined | Overlay content (usually none) |
as? | React.ElementType | 'div' | Polymorphic element type |
container? | HTMLElement | null | document.body | Custom portal container element |
ref? | React.Ref<HTMLElement> | undefined | Ref forwarded to overlay element |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
onClick | (event: React.MouseEvent) | Overlay clicked | Click on overlay background |
HTML Attributes
| Attribute | Value | Purpose |
|---|---|---|
data-state | "open" | "closed" | Current dialog state |
Dialog.Content
Main dialog container that handles focus management and keyboard interactions.
Props
| Name | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | - | Dialog content |
as? | React.ElementType | 'div' | Polymorphic element type |
role? | React.AriaRole | 'dialog' | ARIA role for dialog type |
trapFocus? | boolean | true | Enable focus trapping |
restoreFocus? | boolean | true | Restore focus on close |
initialFocus? | HTMLElement | (() => HTMLElement) | undefined | Element to focus on open |
finalFocus? | HTMLElement | (() => HTMLElement) | undefined | Element to focus on close |
container? | HTMLElement | null | document.body | Custom portal container element |
ref? | React.Ref<HTMLElement> | undefined | Ref forwarded to content element |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
onOpenAutoFocus | (event: Event) | Before auto-focus on open | Dialog opens |
onCloseAutoFocus | (event: Event) | Before focus restore on close | Dialog closes |
onEscapeKeyDown | (event: KeyboardEvent) | Escape key pressed | Escape key interaction |
onPointerDownOutside | (event: PointerEvent) | Pointer down outside content | Outside interaction |
onInteractOutside | (event: PointerEvent) | Interaction outside content | Outside interaction with preventDefault |
HTML Attributes
| Attribute | Value | Purpose |
|---|---|---|
data-state | "open" | "closed" | Current dialog state |
data-modal | "true" | "false" | Indicates whether the dialog is modal |
data-role | string | ARIA role value applied to the element |
Dialog.Title
Dialog title that provides an accessible name for the dialog.
Props
| Name | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | - | Title content |
as? | React.ElementType | 'h2' | Polymorphic element type |
level? | number | 2 | Heading level (1-6) |
ref? | React.Ref<HTMLElement> | undefined | Ref forwarded to title element |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
| - | - | No events | - |
HTML Attributes
| Attribute | Value | Purpose |
|---|---|---|
data-level | string | Heading level applied to the title element |
Dialog.Description
Dialog description that provides additional accessible information about the dialog.
Props
| Name | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | - | Description content |
as? | React.ElementType | 'p' | Polymorphic element type |
ref? | React.Ref<HTMLElement> | undefined | Ref forwarded to description element |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
| - | - | No events | - |
Dialog.Close
Button that closes the dialog when activated. Extends all Button component
props including polymorphic rendering via the as prop.
Props
| Name | Type | Default | Description |
|---|---|---|---|
as? | React.ElementType | 'button' | Polymorphic element type |
children | React.ReactNode | ((state: DialogCloseRenderProps) => React.ReactNode) | - | Close button content or render props function |
disabled? | boolean | false | Whether close button is disabled |
autoFocus? | boolean | false | Whether the button should receive focus on mount |
isLoading? | boolean | false | Loading state with screen reader support |
isPressed? | boolean | undefined | Toggle state - creates a toggle button when defined |
onPressedChange? | (pressed: boolean) => void | undefined | Callback fired when toggle state changes |
ref? | React.Ref<HTMLElement> | undefined | Ref forwarded to close button element |
...props | ButtonProps | - | All standard Button component attributes |
Render Props (DialogCloseRenderProps)
| Property | Type | Description |
|---|---|---|
isOpen | boolean | Whether the dialog is currently visible |
close | () => void | Function to programmatically close the dialog |
Events
| Name | Parameters | Description | When Triggered |
|---|---|---|---|
onClick | (event: React.MouseEvent) | Close button clicked | Mouse click |
onKeyDown | (event: React.KeyboardEvent) | Key pressed on close button | Keyboard interaction |
HTML Attributes
| Attribute | Value | Purpose |
|---|---|---|
data-dialog-close | "" | Always present, marks the close button |
data-disabled | "" | Present when disabled |
data-loading | "" | Present when loading |
data-pressed | "" | Present when toggle button is active |
data-autofocus | "" | Present when autoFocus is true |
Keyboard Interactions
Complete keyboard behavior for the entire Dialog component:
| Key | Action | Context | Notes |
|---|---|---|---|
Tab | Navigate forward | Dialog content | Moves focus through interactive elements within dialog |
Shift + Tab | Navigate backward | Dialog content | Moves focus backward through elements within dialog |
Enter | Activate | Trigger/Close buttons | Opens or closes dialog |
Space | Activate | Trigger/Close buttons | Alternative activation method for buttons |
Escape | Close dialog | Dialog open | Closes dialog and returns focus to trigger |
Focus Management:
- When dialog opens, focus moves to the first focusable element or
initialFocuselement - Focus is trapped within the dialog content while open
- Tab cycling is constrained to dialog content
- When dialog closes, focus returns to the trigger or
finalFocuselement - Focus restoration can be customized or disabled via props