Skip to main content

Dialog

A headless modal and non-modal dialog component that provides accessibility features and focus management.

Live Demo​

JavaScript
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 as prop
  • ✅ 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:

Parts
RootContainer managing dialog state and context
TriggerButton that opens the dialog
OverlayBackground overlay behind dialog content
ContentMain dialog container with focus management
TitleDialog title for accessibility
DescriptionDialog description for accessibility
CloseButton that closes the dialog

Structure​

<Dialog.Root>
<Dialog.Trigger />
<Dialog.Overlay />
<Dialog.Content>
<Dialog.Title />
<Dialog.Description />
<Dialog.Close />
</Dialog.Content>
</Dialog.Root>

Data Flow:

  • Dialog.Root manages open/close state and provides context to all child components
  • Dialog.Trigger toggles the dialog state and maintains focus reference
  • Dialog.Overlay provides background overlay with click-outside-to-close behavior (portals to document.body by default)
  • Dialog.Content handles focus management and keyboard interactions (portals to document.body by default)
  • Dialog.Title and Dialog.Description provide accessible labeling
  • Dialog.Close provides 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

NameTypeDefaultDescription
childrenReact.ReactNode-Dialog trigger, overlay, and content components
id?stringauto-generatedCustom base ID for ARIA relationships; sub-IDs are derived as ${id}-title, ${id}-description, ${id}-content
open?booleanundefinedControlled open state
onOpenChange?(open: boolean) => voidundefinedCallback when open state changes
defaultOpen?booleanfalseInitial open state for uncontrolled usage
modal?booleantrueWhether dialog is modal (blocks interaction outside)
disabled?booleanfalseDisables all dialog triggers (prevents opening)
forceMount?booleanfalseAlways render portal/overlay/content for animation libraries

Events

NameParametersDescriptionWhen Triggered
onOpenChange(open: boolean)Open state changesUser 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

NameTypeDefaultDescription
childrenReact.ReactNode | ((state: DialogTriggerRenderProps) => React.ReactNode)-Trigger content or render props function
disabled?booleanfalseDisables trigger interaction
autoFocus?booleanfalseWhether the button should receive focus on mount
isLoading?booleanfalseLoading state with screen reader support
isPressed?booleanundefinedToggle state - creates a toggle button when defined
onPressedChange?(pressed: boolean) => voidundefinedCallback fired when toggle state changes
ref?React.Ref<HTMLElement>undefinedRef forwarded to trigger element
...propsButtonProps-All standard Button component attributes

Render Props (DialogTriggerRenderProps)

PropertyTypeDescription
isOpenbooleanWhether the dialog is currently visible
disabledbooleanWhether the trigger is disabled
open() => voidFunction to programmatically open the dialog (no-op while disabled)
close() => voidFunction to programmatically close the dialog
toggle() => voidFunction to programmatically toggle the dialog (no-op while disabled)

Events

NameParametersDescriptionWhen Triggered
onClick(event: React.MouseEvent)Trigger clickedMouse click
onKeyDown(event: React.KeyboardEvent)Key pressed on triggerKeyboard interaction

HTML Attributes

AttributeValuePurpose
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

NameTypeDefaultDescription
children?React.ReactNodeundefinedOverlay content (usually none)
as?React.ElementType'div'Polymorphic element type
container?HTMLElement | nulldocument.bodyCustom portal container element
ref?React.Ref<HTMLElement>undefinedRef forwarded to overlay element

Events

NameParametersDescriptionWhen Triggered
onClick(event: React.MouseEvent)Overlay clickedClick on overlay background

HTML Attributes

AttributeValuePurpose
data-state"open" | "closed"Current dialog state

Dialog.Content​

Main dialog container that handles focus management and keyboard interactions.

Props

NameTypeDefaultDescription
childrenReact.ReactNode-Dialog content
as?React.ElementType'div'Polymorphic element type
role?React.AriaRole'dialog'ARIA role for dialog type
trapFocus?booleantrueEnable focus trapping
restoreFocus?booleantrueRestore focus on close
initialFocus?HTMLElement | (() => HTMLElement)undefinedElement to focus on open
finalFocus?HTMLElement | (() => HTMLElement)undefinedElement to focus on close
container?HTMLElement | nulldocument.bodyCustom portal container element
ref?React.Ref<HTMLElement>undefinedRef forwarded to content element

Events

NameParametersDescriptionWhen Triggered
onOpenAutoFocus(event: Event)Before auto-focus on openDialog opens
onCloseAutoFocus(event: Event)Before focus restore on closeDialog closes
onEscapeKeyDown(event: KeyboardEvent)Escape key pressedEscape key interaction
onPointerDownOutside(event: PointerEvent)Pointer down outside contentOutside interaction
onInteractOutside(event: PointerEvent)Interaction outside contentOutside interaction with preventDefault

HTML Attributes

AttributeValuePurpose
data-state"open" | "closed"Current dialog state
data-modal"true" | "false"Indicates whether the dialog is modal
data-rolestringARIA role value applied to the element

Dialog.Title​

Dialog title that provides an accessible name for the dialog.

Props

NameTypeDefaultDescription
childrenReact.ReactNode-Title content
as?React.ElementType'h2'Polymorphic element type
level?number2Heading level (1-6)
ref?React.Ref<HTMLElement>undefinedRef forwarded to title element

Events

NameParametersDescriptionWhen Triggered
--No events-

HTML Attributes

AttributeValuePurpose
data-levelstringHeading level applied to the title element

Dialog.Description​

Dialog description that provides additional accessible information about the dialog.

Props

NameTypeDefaultDescription
childrenReact.ReactNode-Description content
as?React.ElementType'p'Polymorphic element type
ref?React.Ref<HTMLElement>undefinedRef forwarded to description element

Events

NameParametersDescriptionWhen 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

NameTypeDefaultDescription
as?React.ElementType'button'Polymorphic element type
childrenReact.ReactNode | ((state: DialogCloseRenderProps) => React.ReactNode)-Close button content or render props function
disabled?booleanfalseWhether close button is disabled
autoFocus?booleanfalseWhether the button should receive focus on mount
isLoading?booleanfalseLoading state with screen reader support
isPressed?booleanundefinedToggle state - creates a toggle button when defined
onPressedChange?(pressed: boolean) => voidundefinedCallback fired when toggle state changes
ref?React.Ref<HTMLElement>undefinedRef forwarded to close button element
...propsButtonProps-All standard Button component attributes

Render Props (DialogCloseRenderProps)

PropertyTypeDescription
isOpenbooleanWhether the dialog is currently visible
close() => voidFunction to programmatically close the dialog

Events

NameParametersDescriptionWhen Triggered
onClick(event: React.MouseEvent)Close button clickedMouse click
onKeyDown(event: React.KeyboardEvent)Key pressed on close buttonKeyboard interaction

HTML Attributes

AttributeValuePurpose
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:

KeyActionContextNotes
TabNavigate forwardDialog contentMoves focus through interactive elements within dialog
Shift + TabNavigate backwardDialog contentMoves focus backward through elements within dialog
EnterActivateTrigger/Close buttonsOpens or closes dialog
SpaceActivateTrigger/Close buttonsAlternative activation method for buttons
EscapeClose dialogDialog openCloses dialog and returns focus to trigger

Focus Management:

  • When dialog opens, focus moves to the first focusable element or initialFocus element
  • 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 finalFocus element
  • Focus restoration can be customized or disabled via props