Dialog (대화상자)
주요 콘텐츠 위에 나타나는 모달 창 컴포넌트예요. 확인·경고 알림, 폼, 설정 등 사용자의 주의가 필요한 콘텐츠를 겹쳐서 표시해요.
출처: 문서
본문
구조 (Anatomy)
<Dialog.Root>
<Dialog.Trigger />
<Dialog.Backdrop />
<Dialog.Positioner>
<Dialog.Content>
<Dialog.Title />
<Dialog.Description />
<Dialog.CloseTrigger />
</Dialog.Content>
</Dialog.Positioner>
</Dialog.Root>
예제 (Examples)
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const Basic = () => (
<Dialog.Root>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Welcome Back</Dialog.Title>
<Dialog.Description className={styles.Description}>Sign in to your account to continue.</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
제어 (Controlled)
open과 onOpenChange prop을 사용해 대화상자 상태를 관리할 수 있어요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const Controlled = () => {
const [open, setOpen] = useState(false)
return (
<Dialog.Root open={open} onOpenChange={(e) => setOpen(e.open)}>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Session Settings</Dialog.Title>
<Dialog.Description className={styles.Description}>
Manage your session preferences and security options.
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
}
RootProvider
대화상자를 제어하는 또 다른 방법으로 RootProvider 컴포넌트와 useDialog 훅을 사용할 수 있어요. 이렇게 하면 컴포넌트 외부에서도 상태와 메서드에 접근할 수 있어요.
import { Dialog, useDialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const RootProvider = () => {
const dialog = useDialog()
return (
<div className="stack">
<button className={button.Root} onClick={() => dialog.setOpen(true)}>
Dialog is {dialog.open ? 'open' : 'closed'}
</button>
<Dialog.RootProvider value={dialog}>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Controlled Externally</Dialog.Title>
<Dialog.Description className={styles.Description}>
This dialog is controlled via the useDialog hook.
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.RootProvider>
</div>
)
}
알림 대화상자 (Alert Dialog)
중요한 확인이나 파괴적인 작업에는 role="alertdialog"를 사용하세요. 알림 대화상자는 일반 대화상자와 중요한 차이가 있어요:
- 자동 포커스: 열릴 때 닫기/취소 버튼이 포커스를 받아, 가장 안전한 작업을 우선시해요
- 명시적 닫기 필수: 외부 클릭으로 닫을 수 없고, 버튼 클릭이나 Escape 키로만 닫을 수 있어요
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const AlertDialog = () => (
<Dialog.Root role="alertdialog">
<Dialog.Trigger className={button.Root}>Delete Account</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.Title className={styles.Title}>Are you absolutely sure?</Dialog.Title>
<Dialog.Description className={styles.Description}>
This action cannot be undone. This will permanently delete your account and remove your data from our
servers.
</Dialog.Description>
<div className={styles.Actions}>
<Dialog.CloseTrigger className={button.Root}>Cancel</Dialog.CloseTrigger>
<button className={button.Root} data-variant="solid">
Delete Account
</button>
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
지연 마운트 (Lazy Mount)
lazyMount를 사용하면 처음 열릴 때만 대화상자 콘텐츠를 렌더링해요. unmountOnExit와 함께 사용하면 닫힐 때 마운트를 해제해 리소스를 확보해요. Dialog.Root를 조건부로 렌더링하는 것보다 이 방법을 선호해요 — 조건부 렌더링을 참고하세요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const LazyMount = () => (
<Dialog.Root lazyMount unmountOnExit>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Lazy Loaded</Dialog.Title>
<Dialog.Description className={styles.Description}>
This dialog content is only mounted when opened and unmounts on close.
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
초기 포커스 (Initial Focus)
initialFocusEl을 사용해 대화상자가 열릴 때 포커스를 받을 요소를 제어할 수 있어요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import { useRef } from 'react'
import button from 'styles/button.module.css'
import field from 'styles/field.module.css'
import styles from 'styles/dialog.module.css'
export const InitialFocus = () => {
const inputRef = useRef<HTMLInputElement>(null)
return (
<Dialog.Root initialFocusEl={() => inputRef.current}>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Edit Profile</Dialog.Title>
<Dialog.Description className={styles.Description}>
The first input will be focused when the dialog opens.
</Dialog.Description>
<div className={styles.Body}>
<input ref={inputRef} className={field.Input} placeholder="Enter your name..." />
<input className={field.Input} placeholder="Enter your email..." />
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
}
최종 포커스 (Final Focus)
finalFocusEl을 사용해 대화상자가 닫힐 때 포커스를 받을 요소를 제어할 수 있어요. 기본값은 트리거 요소예요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import { useRef } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const FinalFocus = () => {
const finalRef = useRef<HTMLButtonElement>(null)
return (
<div className="stack">
<button className={button.Root} ref={finalRef}>
I will receive focus when dialog closes
</button>
<Dialog.Root finalFocusEl={() => finalRef.current}>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Focus Redirect</Dialog.Title>
<Dialog.Description className={styles.Description}>
When this dialog closes, focus will return to the button above instead of the trigger.
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
</div>
)
}
비모달 (Non-Modal)
modal={false}를 사용하면 대화상자 외부 요소와의 상호작용을 허용할 수 있어요. 포커스 트래핑과 스크롤 방지를 비활성화해요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const NonModal = () => (
<Dialog.Root modal={false}>
<Dialog.Trigger className={button.Root}>Open Non-Modal Dialog</Dialog.Trigger>
<Portal>
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Non-Modal Dialog</Dialog.Title>
<Dialog.Description className={styles.Description}>
This dialog allows interaction with elements outside. You can click buttons, select text, and interact with
the page behind it.
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
내부 스크롤 (Inside Scroll)
maxHeight와 overflow: auto를 사용해 헤더와 푸터는 고정하고 콘텐츠 영역만 스크롤 가능하게 만들 수 있어요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const InsideScroll = () => (
<Dialog.Root>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content} style={{ maxHeight: 'min(32rem, calc(100vh - 4rem))' }}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Terms of Service</Dialog.Title>
<Dialog.Description className={styles.Description}>
Please review our terms before continuing.
</Dialog.Description>
<div className={styles.ScrollContainer}>
{CONTENT_SECTIONS.map((item) => (
<section key={item.title} className={styles.ScrollSection}>
<h3>{item.title}</h3>
<p>{item.body}</p>
</section>
))}
</div>
<div className={styles.Actions}>
<Dialog.CloseTrigger className={button.Root}>Decline</Dialog.CloseTrigger>
<Dialog.CloseTrigger className={button.Root} data-variant="solid">
Accept
</Dialog.CloseTrigger>
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
const CONTENT_SECTIONS = [
{
title: '1. Acceptance of Terms',
body: 'By accessing and using this service, you accept and agree to be bound by the terms and provisions of this agreement.',
},
{
title: '2. Use License',
body: 'Permission is granted to temporarily use this service for personal, non-commercial purposes only. This is the grant of a license, not a transfer of title.',
},
{
title: '3. User Responsibilities',
body: 'You are responsible for maintaining the confidentiality of your account and password. You agree to accept responsibility for all activities that occur under your account.',
},
{
title: '4. Privacy Policy',
body: 'Your use of this service is also governed by our Privacy Policy. Please review our Privacy Policy, which also governs the site and informs users of our data collection practices.',
},
{
title: '5. Limitations',
body: 'In no event shall we be liable for any damages arising out of the use or inability to use the materials on this service.',
},
{
title: '6. Revisions',
body: 'We may revise these terms of service at any time without notice. By using this service you are agreeing to be bound by the then current version of these terms.',
},
{
title: '7. Governing Law',
body: 'These terms and conditions are governed by and construed in accordance with applicable laws and you irrevocably submit to the exclusive jurisdiction of the courts.',
},
]
외부 스크롤 (Outside Scroll)
포지셔너를 스크롤 가능하게 만들어 대화상자가 뷰포트 밖으로 확장될 수 있게 해요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import { useRef } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const OutsideScroll = () => {
const contentRef = useRef<HTMLDivElement | null>(null)
return (
<Dialog.Root initialFocusEl={() => contentRef.current}>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.OutsideScrollPositioner}>
<Dialog.Content
ref={contentRef}
className={styles.Content}
style={{ margin: '4rem auto', maxHeight: 'none' }}
>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Privacy Policy</Dialog.Title>
<Dialog.Description className={styles.Description}>
This layout allows the dialog to extend beyond the viewport while keeping the outer container scrollable.
</Dialog.Description>
<div className={styles.Body}>
{CONTENT_SECTIONS.map((item) => (
<section key={item.title} className={styles.ScrollSection}>
<h3>{item.title}</h3>
<p>{item.body}</p>
</section>
))}
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
}
const CONTENT_SECTIONS = [
{
title: '1. Information We Collect',
body: 'We collect information you provide directly, such as when you create an account, make a purchase, or contact us for support. This may include your name, email address, and payment information.',
},
{
title: '2. How We Use Your Information',
body: 'We use the information we collect to provide and improve our services, process transactions, send communications, and personalize your experience.',
},
{
title: '3. Information Sharing',
body: 'We do not sell your personal information. We may share information with service providers who assist in our operations, or when required by law.',
},
{
title: '4. Data Security',
body: 'We implement appropriate technical and organizational measures to protect your personal information against unauthorized access, alteration, or destruction.',
},
{
title: '5. Your Rights',
body: 'You have the right to access, correct, or delete your personal information. You may also opt out of marketing communications at any time.',
},
{
title: '6. Cookies and Tracking',
body: 'We use cookies and similar technologies to enhance your experience, analyze usage patterns, and deliver targeted content. You can manage cookie preferences in your browser settings.',
},
{
title: '7. Third-Party Services',
body: 'Our service may contain links to third-party websites. We are not responsible for the privacy practices of these external sites.',
},
{
title: '8. Children Privacy',
body: 'Our services are not directed to children under 13. We do not knowingly collect personal information from children without parental consent.',
},
{
title: '9. International Transfers',
body: 'Your information may be transferred to and processed in countries other than your own. We ensure appropriate safeguards are in place for such transfers.',
},
{
title: '10. Changes to This Policy',
body: 'We may update this privacy policy from time to time. We will notify you of significant changes by posting a notice on our website or sending you an email.',
},
{
title: '11. Data Retention',
body: 'We retain your personal information for as long as necessary to fulfill the purposes outlined in this policy, unless a longer retention period is required by law.',
},
{
title: '12. Contact Us',
body: 'If you have questions about this privacy policy or our data practices, please contact our privacy team through the support channels provided on our website.',
},
]
컨텍스트 (Context)
Dialog.Context나 useDialogContext 훅으로 대화상자의 상태와 메서드에 접근할 수 있어요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const Context = () => (
<Dialog.Root>
<Dialog.Trigger className={button.Root}>Open Dialog</Dialog.Trigger>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Status</Dialog.Title>
<Dialog.Description className={styles.Description}>
<Dialog.Context>{(dialog) => <span>Dialog is {dialog.open ? 'open' : 'closed'}</span>}</Dialog.Context>
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
메뉴에서 열기 (Open from Menu)
onClick 핸들러를 사용해 메뉴 항목에서 명령적으로 대화상자를 열 수 있어요.
import { Dialog } from '@ark-ui/react/dialog'
import { Menu } from '@ark-ui/react/menu'
import { Portal } from '@ark-ui/react/portal'
import { ChevronDownIcon, XIcon } from 'lucide-react'
import { useState } from 'react'
import dialog from 'styles/dialog.module.css'
import menu from 'styles/menu.module.css'
export const OpenFromMenu = () => {
const [open, setOpen] = useState(false)
return (
<>
<Menu.Root>
<Menu.Trigger className={menu.Trigger}>
Actions
<Menu.Indicator className={menu.Indicator}>
<ChevronDownIcon />
</Menu.Indicator>
</Menu.Trigger>
<Portal>
<Menu.Positioner>
<Menu.Content className={menu.Content}>
<Menu.Item className={menu.Item} value="edit">
Edit
</Menu.Item>
<Menu.Item className={menu.Item} value="duplicate">
Duplicate
</Menu.Item>
<Menu.Separator className={menu.Separator} />
<Menu.Item className={menu.Item} value="delete" onClick={() => setOpen(true)}>
Delete...
</Menu.Item>
</Menu.Content>
</Menu.Positioner>
</Portal>
</Menu.Root>
<Dialog.Root open={open} onOpenChange={(e) => setOpen(e.open)} role="alertdialog">
<Portal>
<Dialog.Backdrop className={dialog.Backdrop} />
<Dialog.Positioner className={dialog.Positioner}>
<Dialog.Content className={dialog.Content}>
<Dialog.Title className={dialog.Title}>Confirm Delete</Dialog.Title>
<Dialog.Description className={dialog.Description}>
Are you sure you want to delete this item? This action cannot be undone.
</Dialog.Description>
<Dialog.CloseTrigger className={dialog.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
</>
)
}
중첩 (Nested)
대화상자를 서로 중첩할 수 있어요. 부모는 줌아웃 같은 스타일 효과를 위해 data-has-nested와 --nested-layer-count CSS 변수를 받아요:
[data-part='content'][data-has-nested] {
transform: scale(calc(1 - var(--nested-layer-count) * 0.05));
}
import { Dialog, useDialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
export const Nested = () => {
const parentDialog = useDialog()
const childDialog = useDialog()
return (
<>
<button className={button.Root} onClick={() => parentDialog.setOpen(true)}>
Open Parent Dialog
</button>
<Dialog.RootProvider value={parentDialog}>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Parent Dialog</Dialog.Title>
<Dialog.Description className={styles.Description}>
This is the parent dialog. Open a nested dialog to see automatic z-index management.
</Dialog.Description>
<div className={styles.Body}>
<button className={button.Root} onClick={() => childDialog.setOpen(true)}>
Open Nested Dialog
</button>
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.RootProvider>
<Dialog.RootProvider value={childDialog}>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Nested Dialog</Dialog.Title>
<Dialog.Description className={styles.Description}>
This dialog is nested within the parent with proper z-index layering.
</Dialog.Description>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.RootProvider>
</>
)
}
여러 트리거 (Multiple Triggers)
하나의 대화상자를 여러 트리거 요소와 공유할 수 있어요. 각 Dialog.Trigger에 value를 전달하고, onTriggerValueChange를 사용해 어떤 트리거가 클릭됐는지에 따라 대화상자 콘텐츠를 업데이트해요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/dialog.module.css'
import field from 'styles/field.module.css'
interface User {
id: string
name: string
email: string
}
const users: User[] = [
{ id: '1', name: 'Alice Johnson', email: 'alice@example.com' },
{ id: '2', name: 'Bob Smith', email: 'bob@example.com' },
{ id: '3', name: 'Carol Davis', email: 'carol@example.com' },
]
export const MultipleTriggers = () => {
const [activeUser, setActiveUser] = useState<User | null>(null)
return (
<Dialog.Root
onTriggerValueChange={(e) => {
setActiveUser(users.find((u) => u.id === e.value) ?? null)
}}
>
<div className={button.Group}>
{users.map((user) => (
<Dialog.Trigger key={user.id} value={user.id} className={button.Root}>
Edit {user.name}
</Dialog.Trigger>
))}
</div>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.Title className={styles.Title}>Edit User</Dialog.Title>
<Dialog.Description className={styles.Description}>Update the user's information below.</Dialog.Description>
{activeUser && (
<>
<div className={styles.Body}>
<div className={field.Root}>
<label className={field.Label}>Name</label>
<input className={field.Input} value={activeUser.name} />
</div>
<div className={field.Root}>
<label className={field.Label}>Email</label>
<input className={field.Input} value={activeUser.email} />
</div>
</div>
<div className={styles.Actions}>
<Dialog.CloseTrigger className={button.Root}>Cancel</Dialog.CloseTrigger>
<Dialog.CloseTrigger className={button.Root} data-variant="solid">
Save Changes
</Dialog.CloseTrigger>
</div>
</>
)}
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
}
확인 (Confirmation)
닫기 시도를 가로채서 확인 프롬프트를 표시하면 저장되지 않은 변경으로 인한 데이터 손실을 방지할 수 있어요.
import { Dialog, useDialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
import { XIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import field from 'styles/field.module.css'
import styles from 'styles/dialog.module.css'
export const Confirmation = () => {
const [formContent, setFormContent] = useState('')
const [isParentDialogOpen, setIsParentDialogOpen] = useState(false)
const parentDialog = useDialog({
open: isParentDialogOpen,
onOpenChange: (details) => {
if (!details.open && formContent.trim()) {
confirmDialog.setOpen(true)
} else {
setIsParentDialogOpen(details.open)
}
},
})
const confirmDialog = useDialog()
const handleConfirmClose = () => {
confirmDialog.setOpen(false)
parentDialog.setOpen(false)
setFormContent('')
}
return (
<>
<button className={button.Root} onClick={() => parentDialog.setOpen(true)}>
Open Form
</button>
<Dialog.RootProvider value={parentDialog}>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Edit Content</Dialog.Title>
<Dialog.Description className={styles.Description}>
Make changes to your content. You'll be asked to confirm before closing if there are unsaved changes.
</Dialog.Description>
<div className={styles.Body}>
<textarea
className={field.Textarea}
value={formContent}
onChange={(e) => setFormContent(e.target.value)}
placeholder="Enter some text..."
rows={4}
/>
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.RootProvider>
<Dialog.RootProvider value={confirmDialog}>
<Portal>
<Dialog.Backdrop className={styles.Backdrop} />
<Dialog.Positioner className={styles.Positioner}>
<Dialog.Content className={styles.Content}>
<Dialog.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Dialog.CloseTrigger>
<Dialog.Title className={styles.Title}>Unsaved Changes</Dialog.Title>
<Dialog.Description className={styles.Description}>
You have unsaved changes. Are you sure you want to close without saving?
</Dialog.Description>
<div className={styles.Actions}>
<button className={button.Root} onClick={() => confirmDialog.setOpen(false)}>
Keep Editing
</button>
<button className={button.Root} data-variant="solid" onClick={handleConfirmClose}>
Discard Changes
</button>
</div>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.RootProvider>
</>
)
}
가이드 (Guides)
닫기 동작 (Close Behavior)
closeOnEscape={false}- Escape 키로 닫히는 것을 방지해요closeOnInteractOutside={false}- 외부 클릭으로 닫히는 것을 방지해요
조건부 제어가 필요하다면 onEscapeKeyDown이나 onInteractOutside에서 e.preventDefault()를 사용하세요.
조건부 렌더링 (Conditional Rendering)
열림 상태를 토글할 때 Dialog.Root를 마운트 해제하면 포커스·스크롤 잠금·정리 작업이 깨질 수 있어요. 루트를 마운트된 상태로 유지하고 open / onOpenChange로 제어하세요.
닫혔을 때 포털 콘텐츠를 DOM에서 제거하고 싶다면 루트에 lazyMount와 unmountOnExit를 추가하세요.
import { Dialog } from '@ark-ui/react/dialog'
import { Portal } from '@ark-ui/react/portal'
// ❌ Avoid
const Dont = () => {
if (isOpen) {
return (
<Dialog.Root open={isOpen} onOpenChange={(e) => setOpen(e.open)}>
<Portal>...</Portal>
</Dialog.Root>
)
}
return null
}
// ✅ Prefer
const Do = () => {
return (
<Dialog.Root open={isOpen} onOpenChange={(e) => setOpen(e.open)} lazyMount unmountOnExit>
<Portal>...</Portal>
</Dialog.Root>
)
}
Z-Index 스태킹 (Z-Index Stacking)
--layer-index와 공유 오버레이 z-index를 사용해 중첩된 대화상자와 중첩 오버레이의 순서를 유지하세요:
[data-scope='dialog'][data-part='content'] {
z-index: calc(var(--z-index-overlay) + var(--layer-index, 0));
}
[data-scope='dialog'][data-part='positioner'] {
z-index: var(--z-index, var(--z-index-overlay));
}
[data-scope='dialog'][data-part='backdrop'] {
z-index: calc(var(--z-index, var(--z-index-overlay)) - 1);
}
자세한 내용은 스타일링 가이드를 참고하세요.
동적 임포트 (Dynamic Imports)
lazyMount를 React.lazy나 Next.js dynamic과 함께 사용할 때는 임포트한 컴포넌트를 Suspense로 감싸세요:
import { Dialog } from '@ark-ui/react/dialog'
import { Suspense } from 'react'
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('./HeavyComponent'))
export const Demo = () => (
<Dialog.Root lazyMount>
<Dialog.Trigger>Open</Dialog.Trigger>
<Dialog.Content>
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
</Suspense>
</Dialog.Content>
</Dialog.Root>
)
API 참조 (API Reference)
Props
Root
Props
aria-label
Type: string
Required: false
Default Value: undefined
Description: 대화상자 제목이 렌더링되지 않을 경우를 대비한 사람이 읽을 수 있는 대화상자 레이블이에요.
closeOnEscape
Type: boolean
Required: false
Default Value: true
Description: Escape 키를 눌렀을 때 대화상자를 닫을지 여부예요.
closeOnInteractOutside
Type: boolean
Required: false
Default Value: true
Description: 외부가 클릭됐을 때 대화상자를 닫을지 여부예요.
defaultOpen
Type: boolean
Required: false
Default Value: false
Description: 렌더링될 때 대화상자의 초기 열림 상태예요.
대화상자의 열림 상태를 직접 제어할 필요가 없을 때 사용해요.
defaultTriggerValue
Type: string
Required: false
Default Value: undefined
Description: 렌더링될 때의 초기 활성 트리거 값이에요.
활성 트리거 값을 직접 제어할 필요가 없을 때 사용해요.
finalFocusEl
Type: () => MaybeElement
Required: false
Default Value: undefined
Description: 대화상자가 닫힐 때 포커스를 받을 요소예요.
hideMode
Type: HideMode
Required: false
Default Value: 'display-none'
Description: 마운트되었지만 표시되지 않을 때 콘텐츠를 숨기는 방법이에요.
'display-none': HTMLhidden속성을 사용해요. 이펙트는 계속 동작해요.'activity': React 19<Activity mode="hidden">을 사용해요. 이펙트가 일시 중지돼요. React 19+가 필요해요.
id
Type: string
Required: false
Default Value: undefined
Description: 머신의 고유 식별자예요.
ids
Type: Partial<{ trigger: string | ((value?: string | undefined) => string) positioner: string backdrop: string content: string closeTrigger: string title: string description: string }>
Required: false
Default Value: undefined
Description: 대화상자 안 요소들의 id예요. 컴포지션에 유용해요.
immediate
Type: boolean
Required: false
Default Value: undefined
Description: 현재 변경을 즉시 동기화할지, 아니면 다음 프레임으로 지연할지 여부예요.
initialFocusEl
Type: () => MaybeElement
Required: false
Default Value: undefined
Description: 대화상자가 열릴 때 포커스를 받을 요소예요.
lazyMount
Type: boolean
Required: false
Default Value: false
Description: 지연 마운트를 활성화할지 여부예요.
modal
Type: boolean
Required: false
Default Value: true
Description: 요소 외부에서의 포인터 상호작용을 방지하고 그 아래의 모든 콘텐츠를 숨길지 여부예요.
onEscapeKeyDown
Type: (event: KeyboardEvent) => void
Required: false
Default Value: undefined
Description: Escape 키를 눌렀을 때 호출되는 함수예요.
onExitComplete
Type: VoidFunction
Required: false
Default Value: undefined
Description: 닫힌 상태에서 애니메이션이 끝날 때 호출되는 함수예요.
onFocusOutside
Type: (event: FocusOutsideEvent) => void
Required: false
Default Value: undefined
Description: 포커스가 컴포넌트 외부로 이동됐을 때 호출되는 함수예요.
onInteractOutside
Type: (event: InteractOutsideEvent) => void
Required: false
Default Value: undefined
Description: 컴포넌트 외부에서 상호작용이 발생했을 때 호출되는 함수예요.
onOpenChange
Type: (details: OpenChangeDetails) => void
Required: false
Default Value: undefined
Description: 대화상자의 열림 상태가 변경될 때 호출되는 함수예요.
onPointerDownOutside
Type: (event: PointerDownOutsideEvent) => void
Required: false
Default Value: undefined
Description: 컴포넌트 외부에서 포인터가 눌렸을 때 호출되는 함수예요.
onRequestDismiss
Type: (event: LayerDismissEvent) => void
Required: false
Default Value: undefined
Description: 부모 레이어가 닫혀서 이 레이어가 닫힐 때 호출되는 함수예요.
onTriggerValueChange
Type: (details: TriggerValueChangeDetails) => void
Required: false
Default Value: undefined
Description: 활성 트리거가 변경될 때 호출되는 함수예요.
open
Type: boolean
Required: false
Default Value: undefined
Description: 대화상자의 제어된 열림 상태예요.
persistentElements
Type: (() => Element | null)[]
Required: false
Default Value: undefined
Description: 지속 요소를 반환해요. 지속 요소는:
- 포인터 이벤트를 비활성화하지 않아야 해요
- 닫기(dismiss) 이벤트를 발생시키지 않아야 해요
present
Type: boolean
Required: false
Default Value: undefined
Description: 노드가 존재하는지(사용자가 제어) 여부예요.
preventScroll
Type: boolean
Required: false
Default Value: true
Description: 대화상자가 열렸을 때 그 뒤의 스크롤을 방지할지 여부예요.
restoreFocus
Type: boolean
Required: false
Default Value: undefined
Description: 대화상자가 열리기 전에 포커스가 있던 요소로 포커스를 복원할지 여부예요.
role
Type: 'dialog' | 'alertdialog'
Required: false
Default Value: "dialog"
Description: 대화상자의 역할이에요.
skipAnimationOnMount
Type: boolean
Required: false
Default Value: false
Description: 초기 등장 애니메이션을 허용할지 여부예요.
trapFocus
Type: boolean
Required: false
Default Value: true
Description: 대화상자가 열렸을 때 내부에 포커스를 가둘지 여부예요.
triggerValue
Type: string
Required: false
Default Value: undefined
Description: 제어된 활성 트리거 값이에요.
unmountOnExit
Type: boolean
Required: false
Default Value: false
Description: 종료 시 마운트를 해제할지 여부예요.
Backdrop
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: dialog
data-part: backdrop
data-state: "open" | "closed"
CloseTrigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
Content
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: dialog
data-part: content
data-state: "open" | "closed"
data-nested: dialog
data-has-nested: dialog
Description
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
Positioner
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
RootProvider
Props
value
Type: UseDialogReturn
Required: true
Default Value: undefined
Description: undefined
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
hideMode
Type: HideMode
Required: false
Default Value: 'display-none'
Description: 마운트되었지만 표시되지 않을 때 콘텐츠를 숨기는 방법이에요.
'display-none': HTMLhidden속성을 사용해요. 이펙트는 계속 동작해요.'activity': React 19<Activity mode="hidden">을 사용해요. 이펙트가 일시 중지돼요. React 19+가 필요해요.
immediate
Type: boolean
Required: false
Default Value: undefined
Description: 현재 변경을 즉시 동기화할지, 아니면 다음 프레임으로 지연할지 여부예요.
lazyMount
Type: boolean
Required: false
Default Value: false
Description: 지연 마운트를 활성화할지 여부예요.
onExitComplete
Type: VoidFunction
Required: false
Default Value: undefined
Description: 닫힌 상태에서 애니메이션이 끝날 때 호출되는 함수예요.
present
Type: boolean
Required: false
Default Value: undefined
Description: 노드가 존재하는지(사용자가 제어) 여부예요.
skipAnimationOnMount
Type: boolean
Required: false
Default Value: false
Description: 초기 등장 애니메이션을 허용할지 여부예요.
unmountOnExit
Type: boolean
Required: false
Default Value: false
Description: 종료 시 마운트를 해제할지 여부예요.
Title
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
Trigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
value
Type: string
Required: false
Default Value: undefined
Description: 이 특정 트리거를 식별하는 값이에요.
데이터 속성 (Data Attributes)
data-scope: dialog
data-part: trigger
data-value: 항목의 값이에요.
data-state: "open" | "closed"
data-current: 현재 항목일 때 표시돼요.
Context
API:
| Property | Type | Description |
|---|---|---|
open |
boolean |
대화상자가 열려 있는지 여부예요. |
setOpen |
(open: boolean) => void |
대화상자를 열거나 닫는 함수예요. |
triggerValue |
string | null |
활성 트리거 값이에요. |
setTriggerValue |
(value: string | null) => void |
활성 트리거 값을 설정하는 함수예요. |
접근성 (Accessibility)
Dialog WAI-ARIA 디자인 패턴을 준수해요.
키보드 지원 (Keyboard Support)
Enter
Description: 포커스가 트리거에 있을 때 대화상자를 열어요.
Tab
Description: 콘텐츠 안의 다음 포커스 가능 요소로 포커스를 이동해요. 포커스는 대화상자 안에 갇혀 있어요.
Shift + Tab
Description: 이전 포커스 가능 요소로 포커스를 이동해요. 포커스는 대화상자 안에 갇혀 있어요.
Esc
Description: 대화상자를 닫고 포커스를 트리거나 정의된 최종 포커스 요소로 이동해요.