본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Dialog 문서

원문 보기 위키 갱신

Dialog는 콘텐츠를 표시하거나 사용자 입력을 요청하는 모달 창 컴포넌트예요. 설정, 확인, 폼 입력처럼 주의를 집중해야 하는 작업을 화면 위에 띄워서 처리할 때 특히 유용해요.

출처: 문서

본문

아래 예시에서는 API 키 생성 다이얼로그를 구성해요. 버튼을 누르면 포털로 렌더링된 오버레이와 콘텐츠가 열리고, 제목·설명·입력 필드·닫기 버튼이 함께 나타나요.

<script lang="ts">
  import { Dialog, Label, Separator } from "bits-ui";
  import LockKeyOpen from "phosphor-svelte/lib/LockKeyOpen";
  import X from "phosphor-svelte/lib/X";
</script>
<Dialog.Root>
  <Dialog.Trigger
    class="rounded-input bg-dark text-background
	  shadow-mini hover:bg-dark/95 focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden
	  inline-flex h-12 items-center justify-center whitespace-nowrap px-[21px] text-[15px] font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
  >
    New API key
  </Dialog.Trigger>
  <Dialog.Portal>
    <Dialog.Overlay
      class="data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80"
    />
    <Dialog.Content
      class="rounded-card-lg bg-background shadow-popover data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 outline-hidden fixed left-[50%] top-[50%] z-50 w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] border p-5 sm:max-w-[490px] md:w-full"
    >
      <Dialog.Title
        class="flex w-full items-center justify-center text-lg font-semibold tracking-tight"
      >
        Create API key
      </Dialog.Title>
      <Separator.Root class="bg-muted -mx-5 mb-6 mt-5 block h-px" />
      <Dialog.Description class="text-foreground-alt text-sm">
        Create and manage API keys. You can create multiple keys to organize
        your applications.
      </Dialog.Description>
      <div class="flex flex-col items-start gap-1 pb-11 pt-7">
        <Label.Root for="apiKey" class="text-sm font-medium">API Key</Label.Root
        >
        <div class="relative w-full">
          <input
            id="apiKey"
            class="h-input rounded-card-sm border-border-input bg-background placeholder:text-foreground-alt/50 hover:border-dark-40 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-full items-center border px-4 text-base focus:ring-2 focus:ring-offset-2 sm:text-sm"
            placeholder="secret_api_key"
            name="name"
          />
          <LockKeyOpen
            class="text-dark/30 absolute right-4 top-[14px] size-[22px]"
          />
        </div>
      </div>
      <div class="flex w-full justify-end">
        <Dialog.Close
          class="h-input rounded-input bg-dark text-background shadow-mini hover:bg-dark/95 focus-visible:ring-dark focus-visible:ring-offset-background focus-visible:outline-hidden inline-flex items-center justify-center px-[50px] text-[15px] font-semibold focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
        >
          Save
        </Dialog.Close>
      </div>
      <Dialog.Close
        class="focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden absolute right-5 top-5 rounded-md focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
      >
        <div>
          <X class="text-foreground size-5" />
          <span class="sr-only">Close</span>
        </div>
      </Dialog.Close>
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

개요 (Overview)

Bits UI의 Dialog 컴포넌트는 Svelte 애플리케이션에서 모달 다이얼로그를 유연하고 접근성 있게 만드는 방법을 제공해요. 컴파운드 컴포넌트 패턴을 따라서 다이얼로그의 구조와 동작을 세밀하게 제어하면서도 접근성과 사용 편의성을 함께 유지할 수 있어요.

주요 기능 (Key Features)

  • 컴파운드 컴포넌트 구조: 함께 동작해 완전한 다이얼로그를 만들어 주는 일련의 하위 컴포넌트를 제공해요.
  • 접근성: WAI-ARIA 가이드라인을 염두에 두고 만들어져 키보드 탐색과 스크린 리더를 지원해요.
  • 커스터마이즈 가능: 각 하위 컴포넌트를 독립적으로 스타일링하고 구성할 수 있어요.
  • 포털 지원: 콘텐츠를 포털로 렌더링해 쌓임 맥락(stacking context)을 제대로 유지해요.
  • 포커스 관리: 포커스를 자동으로 관리하고, 필요하면 직접 제어할 수도 있어요.
  • 유연한 상태 관리: 제어/비제어 상태를 모두 지원해 다이얼로그의 열림 상태를 완전히 제어할 수 있어요.

구조 (Architecture)

Dialog 컴포넌트는 각각 특정 역할을 맡은 여러 하위 컴포넌트로 구성돼요.

  • Root: 다이얼로그의 상태를 관리하는 최상위 컨테이너 컴포넌트예요. 모든 하위 컴포넌트에 컨텍스트를 제공해요.
  • Trigger: 다이얼로그의 열림 상태를 토글하는 버튼이에요.
  • Portal: 자식들을 일반적인 DOM 계층 밖인 포털로 렌더링해요.
  • Overlay: 다이얼로그 콘텐츠 뒤에 놓이는 배경이에요.
  • Content: 다이얼로그 콘텐츠를 담는 주요 컨테이너예요.
  • Title: 다이얼로그의 제목을 렌더링해요.
  • Description: 다이얼로그에 대한 설명이나 추가 맥락을 렌더링해요.
  • Close: 다이얼로그를 닫는 버튼이에요.

구조 (Structure)

Dialog 컴포넌트가 코드에서 어떻게 구성되는지 간단히 보여 줄게요.

<script lang="ts">
  import { Dialog } from "bits-ui";
</script>
<Dialog.Root>
  <Dialog.Trigger />
  <Dialog.Portal>
    <Dialog.Overlay />
    <Dialog.Content>
      <Dialog.Title />
      <Dialog.Description />
      <Dialog.Close />
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

재사용 컴포넌트 (Reusable Components)

Bits UI는 커스터마이즈된 재사용형 Dialog 구현을 만들기 위한 토대가 되는 다양한 Dialog 컴포넌트를 제공해요. 이 방식은 애플리케이션 전체에서 일관성과 접근성을 유지하면서도 디자인에 유연성을 더해 줘요.

재사용형 Dialog 만들기 (Building a Reusable Dialog)

다음 예시는 Bits UI의 구성 요소를 사용해 다용도로 쓸 수 있는 재사용 Dialog 컴포넌트를 만드는 방법을 보여 줘요. 이 구현에서는 props와 스니펫을 조합해 컴포넌트 API의 유연성을 활용해요.

<script lang="ts">
  import type { Snippet } from "svelte";
  import { Dialog, type WithoutChild } from "bits-ui";
  type Props = Dialog.RootProps & {
    buttonText: string;
    title: Snippet;
    description: Snippet;
    contentProps?: WithoutChild<Dialog.ContentProps>;
    // ...other component props if you wish to pass them
  };
  let {
    open = $bindable(false),
    children,
    buttonText,
    contentProps,
    title,
    description,
    ...restProps
  }: Props = $props();
</script>
<Dialog.Root bind:open {...restProps}>
  <Dialog.Trigger>
    {buttonText}
  </Dialog.Trigger>
  <Dialog.Portal>
    <Dialog.Overlay />
    <Dialog.Content {...contentProps}>
      <Dialog.Title>
        {@render title()}
      </Dialog.Title>
      <Dialog.Description>
        {@render description()}
      </Dialog.Description>
      {@render children?.()}
      <Dialog.Close>Close Dialog</Dialog.Close>
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

인라인 스니펫으로 사용하기 (Usage with Inline Snippets)

<script lang="ts">
  import MyDialog from "$lib/components/MyDialog.svelte";
</script>
<MyDialog buttonText="Open Dialog">
  {#snippet title()}
    Account settings
  {/snippet}
  {#snippet description()}
    Manage your account settings and preferences.
  {/snippet}
  <!-- Additional dialog content here... -->
</MyDialog>

분리된 스니펫으로 사용하기 (Usage with Separate Snippets)

<script lang="ts">
  import MyDialog from "$lib/components/MyDialog.svelte";
</script>
{#snippet title()}
  Account settings
{/snippet}
{#snippet description()}
  Manage your account settings and preferences.
{/snippet}
<MyDialog buttonText="Open Dialog" {title} {description}>
  <!-- Additional dialog content here... -->
</MyDialog>

모범 사례 (Best Practices)

  • Prop 유연성: 최대한 유연하게 만들기 위해 중첩된 컴포넌트에 props를 받도록 설계해요.
  • 스타일링 옵션: 클래스 오버라이드를 병합하려면 clsx 같은 도구를 사용해요.
  • Prop 바인딩: bind:을 사용하고 $bindable props를 노출해 소비자에게 전체 제어 권한을 줘요.
  • 타입 안전성: Bits UI가 제공하는 내보낸 타입으로 컴포넌트 props를 타입 지정해요.

열림 상태 관리 (Managing Open State)

이번엔 컴포넌트의 open 상태를 관리하는 방법을 알아볼게요.

양방향 바인딩 (Two-Way Binding)

간단하고 자동적인 상태 동기화는 bind:open으로 처리해요.

<script lang="ts">
  import { Dialog } from "bits-ui";
  let isOpen = $state(false);
</script>
<button onclick={() => (isOpen = true)}>Open Dialog</button>
<Dialog.Root bind:open={isOpen}>
  <!-- ... -->
</Dialog.Root>

완전 제어 (Fully Controlled)

상태의 읽기와 쓰기를 전부 제어하고 싶다면 Function Binding을 사용해요.

<script lang="ts">
  import { Dialog } from "bits-ui";
  let myOpen = $state(false);
  function getOpen() {
    return myOpen;
  }
  function setOpen(newOpen: boolean) {
    myOpen = newOpen;
  }
</script>
<Dialog.Root bind:open={getOpen, setOpen}>
  <!-- ... -->
</Dialog.Root>

포커스 관리 (Focus Management)

모달 다이얼로그에서 포커스를 올바르게 관리하는 건 접근성과 사용자 경험에 아주 중요해요. Bits UI의 Dialog 컴포넌트는 포커스를 효과적으로 관리하도록 돕는 여러 기능을 제공해요.

포커스 트랩 (Focus Trap)

기본적으로 Dialog는 WAI-ARIA 모달 다이얼로그 디자인 패턴을 따라 포커스 트랩을 구현해요. 이를 통해 다이얼로그가 열려 있는 동안 키보드 포커스가 다이얼로그 안에 머무르게 되어, 사용자가 페이지의 나머지 부분과 상호작용하지 못하게 해요.

포커스 트랩 끄기 (Disabling the Focus Trap)

권장되진 않지만, 정말로 필요한 경우에는 포커스 트랩을 끌 수 있어요.

<Dialog.Content trapFocus={false}>
  <!-- ... -->
</Dialog.Content>
접근성 경고 (Accessibility Warning)

포커스 트랩을 끄면 접근성이 저하될 수 있어요. 특별한 이유가 있고 대안적인 포커스 관리 전략을 마련한 경우에만 이렇게 하세요.

열릴 때 포커스 (Open Focus)

Dialog가 열리면 자동으로 Dialog.Content 안의 첫 번째 포커스 가능한 요소에 포커스가 이동해요. 덕분에 키보드 사용자는 바로 다이얼로그 내용과 상호작용할 수 있어요.

초기 포커스 커스터마이즈 (Customizing Initial Focus)

Dialog가 열릴 때 어떤 요소에 포커스를 줄지 지정하려면 Dialog.Content의 onOpenAutoFocus prop을 사용해요.

<script lang="ts">
  import { Dialog } from "bits-ui";
  let nameInput = $state<HTMLInputElement>();
</script>
<Dialog.Root>
  <Dialog.Trigger>Open Dialog</Dialog.Trigger>
  <Dialog.Content
    onOpenAutoFocus={(e) => {
      e.preventDefault();
      nameInput?.focus();
    }}
  >
    <input type="text" bind:this={nameInput} />
  </Dialog.Content>
</Dialog.Root>
중요 (Important)

Dialog가 열릴 때 다이얼로그 안의 무언가가 반드시 포커스를 받도록 하세요. 키보드 탐색 맥락을 유지하는 데 필수적이고, 사용자 경험도 훨씬 좋아져요.

닫힐 때 포커스 (Close Focus)

Dialog가 닫히면 포커스는 다이얼로그를 연 요소(보통 Dialog.Trigger)로 돌아가요.

닫힐 때 포커스 커스터마이즈 (Customizing Close Focus)

Dialog가 닫힐 때 포커스를 받을 요소를 바꾸려면 Dialog.Content의 onCloseAutoFocus prop을 사용해요.

<script lang="ts">
  import { Dialog } from "bits-ui";
  let nameInput = $state<HTMLInputElement>();
</script>
<input type="text" bind:this={nameInput} />
<Dialog.Root>
  <Dialog.Trigger>Open Dialog</Dialog.Trigger>
  <Dialog.Content
    onCloseAutoFocus={(e) => {
      e.preventDefault();
      nameInput?.focus();
    }}
  >
    <!-- ... -->
  </Dialog.Content>
</Dialog.Root>

포커스 관리 모범 사례 (Best Practices)

  • Dialog에 대해 명확한 포커스 관리 전략을 항상 유지하세요.
  • 키보드 사용자를 위해 포커스가 예측 가능하고 논리적으로 동작하게 하세요.
  • 키보드 탐색으로 포커스 관리를 직접 테스트해 효과를 검증하세요.

고급 동작 (Advanced Behaviors)

Bits UI의 Dialog 컴포넌트는 동작을 커스터마이즈하고 사용자 경험을 높이는 여러 고급 기능을 제공해요. 이번엔 스크롤 잠금, Escape 키 처리, 다이얼로그 바깥 상호작용을 살펴볼게요.

스크롤 잠금 (Scroll Lock)

기본적으로 Dialog가 열리면 바디의 스크롤이 비활성화돼요. 이렇게 하면 네이티브에 가까운 느낌을 주면서 사용자의 주의를 다이얼로그 콘텐츠에 집중시킬 수 있어요.

스크롤 동작 커스터마이즈 (Customizing Scroll Behavior)

다이얼로그가 열려 있는 동안 바디 스크롤을 허용하려면 Dialog.Content의 preventScroll prop을 사용해요.

<Dialog.Content preventScroll={false}>
  <!-- ... -->
</Dialog.Content>
참고 (Note)

바디 스크롤을 허용하면 사용자 포커스와 접근성에 영향을 줄 수 있어요. 신중하게 사용하세요.

Escape 키 처리 (Escape Key Handling)

기본적으로 Escape 키를 누르면 열린 Dialog가 닫혀요. Bits UI는 이 동작을 커스터마이즈하는 두 가지 방법을 제공해요.

방법 1: escapeKeydownBehavior

escapeKeydownBehavior prop으로 Escape 키를 눌렀을 때 컴포넌트가 취할 동작을 커스터마이즈할 수 있어요. 다음 값 중 하나를 받아요.

  • 'close' (기본값): Dialog를 즉시 닫아요.
  • 'ignore': Dialog가 닫히지 않게 해요.
  • 'defer-otherwise-close': 조상 Bits UI 컴포넌트도 이 prop을 구현하고 있다면 닫기 결정을 그 컴포넌트에 넘겨요. 그렇지 않으면 Dialog를 즉시 닫아요.
  • 'defer-otherwise-ignore': 조상 Bits UI 컴포넌트도 이 prop을 구현하고 있다면 닫기 결정을 그 컴포넌트에 넘겨요. 그렇지 않으면 키 입력을 무시하고 닫지 않아요.

Escape 키를 눌러도 Dialog가 항상 닫히지 않게 하려면 Dialog.Content의 escapeKeydownBehavior prop을 'ignore'로 설정해요.

<Dialog.Content escapeKeydownBehavior="ignore">
  <!-- ... -->
</Dialog.Content>

방법 2: onEscapeKeydown

더 세밀한 제어를 원한다면 onEscapeKeydown prop으로 기본 동작을 재정의할 수 있어요.

<Dialog.Content
  onEscapeKeydown={(e) => {
    e.preventDefault();
    // do something else instead
  }}
>
  <!-- ... -->
</Dialog.Content>

이 방법으로 Escape 키를 눌렀을 때의 커스텀 로직을 구현할 수 있어요.

바깥 상호작용 (Interaction Outside)

기본적으로 Dialog 콘텐츠 영역 바깥과 상호작용하면 Dialog가 닫혀요. Bits UI는 이 동작을 바꾸는 두 가지 방법을 제공해요.

방법 1: interactOutsideBehavior

interactOutsideBehavior prop으로 콘텐츠 바깥에서 상호작용(터치, 마우스, 포인터 이벤트)이 발생했을 때 컴포넌트가 취할 동작을 커스터마이즈할 수 있어요. 다음 값 중 하나를 받아요.

  • 'close' (기본값): Dialog를 즉시 닫아요.
  • 'ignore': Dialog가 닫히지 않게 해요.
  • 'defer-otherwise-close': 조상 Bits UI 컴포넌트도 이 prop을 구현하고 있다면 닫기 결정을 그 컴포넌트에 넘겨요. 그렇지 않으면 Dialog를 즉시 닫아요.
  • 'defer-otherwise-ignore': 조상 Bits UI 컴포넌트도 이 prop을 구현하고 있다면 닫기 결정을 그 컴포넌트에 넘겨요. 그렇지 않으면 이벤트를 무시하고 닫지 않아요.

콘텐츠 바깥에서 상호작용해도 Dialog가 항상 닫히지 않게 하려면 Dialog.Content의 interactOutsideBehavior prop을 'ignore'로 설정해요.

<Dialog.Content interactOutsideBehavior="ignore">
  <!-- ... -->
</Dialog.Content>

방법 2: onInteractOutside

바깥 상호작용을 커스텀하게 처리하려면 onInteractOutside prop으로 기본 동작을 재정의할 수 있어요.

<Dialog.Content
  onInteractOutside={(e) => {
    e.preventDefault();
    // do something else instead
  }}
>
  <!-- ... -->
</Dialog.Content>

이 방식으로 사용자가 Dialog 콘텐츠 바깥과 상호작용할 때의 구체적인 동작을 구현할 수 있어요.

고급 동작 모범 사례 (Best Practices)

  • 스크롤 잠금: 스크롤 잠금을 끄기 전에 사용 사례를 신중하게 고려하세요. 스크롤 가능한 콘텐츠가 있는 다이얼로그나 특정 UX 요구 사항에서는 필요할 수 있어요.
  • Escape 키: 기본 Escape 키 동작을 재정의하는 건 신중하게 하세요. 사용자들은 보통 Escape 키로 모달을 닫을 거라 기대해요.
  • 바깥 상호작용: 바깥 상호작용을 무시하는 건 중요한 다이얼로그나 여러 단계의 프로세스에서 유용할 수 있지만, 사용자를 실수로 가둬 두지 않도록 주의하세요.
  • 접근성: 어떤 커스터마이즈든 다이얼로그의 접근성을 유지하거나 개선하도록 하세요.
  • 사용자 기대: 커스텀 동작과 일반적인 UX 패턴 사이의 균형을 맞춰 사용자가 헷갈리지 않게 하세요.

이런 고급 기능을 활용하면 사용성과 접근성 기준을 유지하면서도 매우 커스터마이즈된 다이얼로그 경험을 만들 수 있어요.

중첩 다이얼로그 (Nested Dialogs)

Dialog는 서로 중첩해서 더 복잡한 사용자 인터페이스를 만들 수 있어요.

<script lang="ts">
  import X from "phosphor-svelte/lib/X";
  import { Dialog } from "bits-ui";
  let rootOpen = $state(false);
  let nestedOpen = $state(false);
</script>
<Dialog.Root bind:open={rootOpen}>
  <Dialog.Trigger
    class="rounded-input bg-dark text-background
	shadow-mini hover:bg-dark/95 focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden
	inline-flex h-12 select-none items-center justify-center whitespace-nowrap px-[21px] text-[15px] font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
  >
    Open First Dialog
  </Dialog.Trigger>
  <Dialog.Portal>
    <Dialog.Overlay
      class="data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-nested:hidden fixed inset-0 z-50 bg-black/80 transition-opacity duration-200"
    />
    <Dialog.Content
      class="rounded-card-lg bg-background shadow-popover data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 outline-hidden fixed left-[50%] top-[50%] z-50 w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[calc(-50%+var(--bits-dialog-nested-count)*-1.5rem)] scale-[calc(1-var(--bits-dialog-nested-count)*0.05)] border p-6 transition-all duration-200 sm:max-w-[500px] md:w-full"
      style="filter: blur(calc(var(--bits-dialog-nested-count) * 1px));"
    >
      <Dialog.Title class="mb-2 text-lg font-semibold tracking-tight">
        First Dialog
      </Dialog.Title>
      <Dialog.Description class="text-foreground-alt mb-6 text-sm">
        This is the first dialog in the nested dialog stack.
      </Dialog.Description>
      <Dialog.Root bind:open={nestedOpen}>
        <Dialog.Trigger
          class="rounded-input bg-dark text-background
				shadow-mini hover:bg-dark/95 focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden
				inline-flex h-12 select-none items-center justify-center whitespace-nowrap px-[21px] text-[15px] font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
        >
          Open Second Dialog
        </Dialog.Trigger>
        <Dialog.Portal>
          <Dialog.Overlay
            class="data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-nested:hidden fixed inset-0 z-50 bg-black/80 transition-opacity duration-200"
          />
          <Dialog.Content
            class="rounded-card-lg bg-background shadow-popover data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 outline-hidden fixed left-[50%] top-[50%] z-50 w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[calc(-50%+var(--bits-dialog-nested-count)*-1rem)] scale-[calc(1-var(--bits-dialog-nested-count)*0.05)] border p-6 transition-all duration-200 sm:max-w-[500px] md:w-full"
            style="filter: blur(calc(var(--bits-dialog-nested-count) * 1.5px));"
          >
            <Dialog.Title class="mb-2 text-lg font-semibold tracking-tight">
              Second Dialog
            </Dialog.Title>
            <Dialog.Description class="text-foreground-alt mb-6 text-sm">
              This is the second dialog in the nested dialog stack.
            </Dialog.Description>
            <Dialog.Close
              class="rounded-input bg-dark text-background
	shadow-mini hover:bg-dark/95 focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden
	inline-flex h-12 select-none items-center justify-center whitespace-nowrap px-[21px] text-[15px] font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
            >
              Close Second Dialog
            </Dialog.Close>
          </Dialog.Content>
        </Dialog.Portal>
      </Dialog.Root>
      <Dialog.Close
        class="focus-visible:ring-foreground focus-visible:ring-offset-background focus-visible:outline-hidden absolute right-5 top-5 rounded-md focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.98]"
      >
        <div>
          <X class="text-foreground size-5" />
          <span class="sr-only">Close</span>
        </div>
      </Dialog.Close>
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

중첩 다이얼로그 스타일링 (Styling Nested Dialogs)

Dialog 컴포넌트는 중첩 정보를 자동으로 추적해서, 다이얼로그가 중첩될 때 시각적 계층을 만드는 데 쓸 수 있어요. 자식 다이얼로그가 열릴 때 부모 다이얼로그를 축소하거나 어둡게 하는 효과를 만드는 데 특히 유용해요.

사용 가능한 스타일링 훅 (Available Styling Hooks)

각 다이얼로그는 다음 데이터 속성과 CSS 변수를 제공해요.

Data Attributes:

  • data-nested-open: 이 다이얼로그 안에 중첩 다이얼로그가 하나 이상 열려 있을 때 Dialog.Content와 Dialog.Overlay에 표시돼요.
  • data-nested: 다이얼로그가 중첩 다이얼로그일 때 Dialog.Content와 Dialog.Overlay에 표시돼요. 중첩 다이얼로그의 오버레이를 숨겨 부모 다이얼로그와 겹치지 않게 할 때 유용해요.

CSS Variables:

  • --bits-dialog-depth: 다이얼로그의 중첩 깊이예요 (루트는 0, 첫 번째 중첩은 1 등).
  • --bits-dialog-nested-count: 이 다이얼로그 안에서 현재 열려 있는 중첩 다이얼로그의 개수예요 (반응형으로 갱신돼요).

예시: 부모 다이얼로그 축소 (Example: Scale Down Parent Dialogs)

<Dialog.Root>
  <Dialog.Trigger>Open Dialog</Dialog.Trigger>
  <Dialog.Portal>
    <Dialog.Overlay class="overlay" />
    <Dialog.Content
      style="transform: scale(calc(1 - var(--bits-dialog-nested-count) * 0.05));
             filter: blur(calc(var(--bits-dialog-nested-count) * 2px));"
    >
      <!-- Dialog content -->
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

이런 스타일링 훅을 활용하면 중첩 다이얼로그의 계층을 사용자가 쉽게 이해할 수 있도록 정교한 시각적 피드백을 만들 수 있어요.

Svelte Transitions

Dialog 컴포넌트는 Svelte의 내장 트랜지션 효과나 다른 애니메이션 라이브러리로 보강할 수 있어요.

forceMount와 child 스니펫 사용하기 (Using forceMount and child Snippets)

Dialog 컴포넌트에 Svelte 트랜지션을 적용하려면 forceMount prop과 child 스니펫을 조합해 사용해요. 이 방식은 Dialog.Content와 Dialog.Overlay의 마운트 동작과 애니메이션을 완전히 제어할 수 있게 해 줘요.

<script lang="ts">
  import { Dialog } from "bits-ui";
  import { fly, fade } from "svelte/transition";
</script>
<Dialog.Root>
  <!-- ... other dialog components -->
  <Dialog.Overlay forceMount>
    {#snippet child({ props, open })}
      {#if open}
        <div {...props} transition:fade>
          <!-- ... -->
        </div>
      {/if}
    {/snippet}
  </Dialog.Overlay>
  <Dialog.Content forceMount>
    {#snippet child({ props, open })}
      {#if open}
        <div {...props} transition:fly>
          <!-- ... -->
        </div>
      {/if}
    {/snippet}
  </Dialog.Content>
</Dialog.Root>

이 예시에서:

  • forceMount prop은 컴포넌트가 항상 DOM에 있게 해 줘요.
  • child 스니펫은 열림 상태와 컴포넌트 props에 접근할 수 있게 해 줘요.
  • Svelte의 #if 블록은 콘텐츠가 언제 보일지를 제어해요.
  • 트랜지션 지시어(transition:fade, transition:fly)로 애니메이션을 적용해요.

트랜지션 모범 사례 (Best Practices)

코드를 더 깔끔하게 유지하고 유지보수성을 높이려면 이런 트랜지션 로직을 캡슐화한 커스텀 재사용 컴포넌트를 만드는 걸 고려해 보세요.

<script lang="ts">
  import { Dialog, type WithoutChildrenOrChild } from "bits-ui";
  import { fade } from "svelte/transition";
  import type { Snippet } from "svelte";
  let {
    ref = $bindable(null),
    duration = 200,
    children,
    ...restProps
  }: WithoutChildrenOrChild<Dialog.OverlayProps> & {
    duration?: number;
    children?: Snippet;
  } = $props();
</script>
<Dialog.Overlay forceMount bind:ref {...restProps}>
  {#snippet child({ props, open })}
    {#if open}
      <div {...props} transition:fade={{ duration }}>
        {@render children?.()}
      </div>
    {/if}
  {/snippet}
</Dialog.Overlay>

만든 MyDialogOverlay 컴포넌트는 다른 Dialog 프리미티브와 함께 애플리케이션 전반에서 이렇게 사용할 수 있어요.

<script lang="ts">
  import { Dialog } from "bits-ui";
  import { MyDialogOverlay } from "$lib/components";
</script>
<Dialog.Root>
  <Dialog.Trigger>Open</Dialog.Trigger>
  <Dialog.Portal>
    <MyDialogOverlay duration={300} />
    <Dialog.Content>
      <!-- ... -->
    </Dialog.Content>
  </Dialog.Portal>
</Dialog.Root>

폼과 함께 사용하기 (Working with Forms)

폼 제출 (Form Submission)

Dialog 컴포넌트를 사용할 때 폼을 제출하거나 비동기 작업을 수행한 뒤 다이얼로그를 닫고 싶은 경우가 많아요.

이것은 비동기 작업이 끝날 때까지 기다린 다음 프로그래밍 방식으로 다이얼로그를 닫는 방식으로 처리할 수 있어요.

<script lang="ts">
	import { Dialog } from "bits-ui";
	function wait(ms: number) {
		return new Promise((resolve) => setTimeout(resolve, ms));
	}
	let open = $state(false);
</script>
<Dialog.Root bind:open>
	<Dialog.Portal>
		<Dialog.Overlay />
		<Dialog.Content>
			<Dialog.Title>Confirm your action</Dialog.Title>
			<Dialog.Description>Are you sure you want to do this?</Dialog.Description>
			<form
				method="POST"
				action="?/someAction"
				onsubmit={() => {
					wait(1000).then(() => (open = false));
				}}
			>
				<button type="submit">Submit form</Dialog.Action>
			</form>
		</Dialog.Content>
	</Dialog.Portal>
</Dialog.Root>

폼 안에서 사용하기 (Inside a Form)

폼 안에서 Dialog를 사용한다면 Portal을 비활성화하거나 Dialog 구조에 포함하지 않아야 해요. Portal은 다이얼로그 콘텐츠를 폼 밖에 렌더링하기 때문에, 이대로 두면 폼이 제대로 제출되지 않아요.

API Reference

Dialog.Root

The root component used to set and manage the state of the dialog.

Property Type Description Details
open $bindable boolean Whether or not the dialog is open.Default: false
onOpenChange function - (open: boolean) => void A callback function called when the open state changes.Default:  —— undefined
onOpenChangeComplete function - (open: boolean) => void A callback function called after the open state changes and all animations have completed.Default:  —— undefined
children Snippet The children content to render.Default:  —— undefined

Dialog.Trigger

The element which opens the dialog on press.

Property Type Description Details
ref $bindable HTMLButtonElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-dialog-trigger '' Present on the trigger.

Dialog.Portal

A portal which renders the dialog into the body when it is open.

Property Type Description Details
to union - Element | string Where to render the content when it is open. Defaults to the body.Default: document.body
disabled boolean Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.Default: false
children Snippet The children content to render.Default:  —— undefined

Dialog.Content

The content displayed within the dialog modal.

Property Type Description Details
onEscapeKeydown function - (event: KeyboardEvent) => void Callback fired when an escape keydown event occurs in the floating content. You can call event.preventDefault() to prevent the default behavior of handling the escape keydown event.Default:  —— undefined
escapeKeydownBehavior enum - 'close' | 'ignore' | 'defer-otherwise-close' | 'defer-otherwise-ignore' The behavior to use when an escape keydown event occurs in the floating content. 'close' will close the content immediately. 'ignore' will prevent the content from closing. 'defer-otherwise-close' will defer to the parent element if it exists, otherwise it will close the content. 'defer-otherwise-ignore' will defer to the parent element if it exists, otherwise it will ignore the interaction.Default: 'close'
onInteractOutside function - (event: PointerEvent) => void Callback fired when an outside interaction event occurs, which is a pointerdown event. You can call event.preventDefault() to prevent the default behavior of handling the outside interaction.Default:  —— undefined
onFocusOutside function - (event: FocusEvent) => void Callback fired when focus leaves the dismissible layer. You can call event.preventDefault() to prevent the default behavior on focus leaving the layer.Default:  —— undefined
interactOutsideBehavior enum - 'close' | 'ignore' | 'defer-otherwise-close' | 'defer-otherwise-ignore' The behavior to use when an interaction occurs outside of the floating content. 'close' will close the content immediately. 'ignore' will prevent the content from closing. 'defer-otherwise-close' will defer to the parent element if it exists, otherwise it will close the content. 'defer-otherwise-ignore' will defer to the parent element if it exists, otherwise it will ignore the interaction.Default: 'close'
onOpenAutoFocus function - (event: Event) => void Event handler called when auto-focusing the content as it is opened. Can be prevented.Default:  —— undefined
onCloseAutoFocus function - (event: Event) => void Event handler called when auto-focusing the content as it is closed. Can be prevented.Default:  —— undefined
trapFocus boolean Whether or not to trap the focus within the content when open.Default: true
forceMount boolean Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.Default: false
preventOverflowTextSelection boolean When true, prevents the text selection from overflowing the bounds of the element.Default: true
preventScroll boolean When true, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.Default: true
restoreScrollDelay number The delay in milliseconds before the scrollbar is restored after closing the dialog. This is only applicable when using the child snippet for custom transitions and preventScroll and forceMount are true. You should set this to a value greater than the transition duration to prevent content from shifting during the transition.Default: 0
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type ChildSnippetProps = { open: boolean; props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-state enum - 'open' | 'closed' The state of the dialog.
data-starting-style '' Present during the initial open frame. Use this to define the starting styles for CSS transitions.
data-ending-style '' Present while closing before unmount. Use this to define the ending styles for CSS transitions.
data-dialog-content '' Present on the content.
data-nested-open '' Present when one or more nested dialogs are open within this dialog. Can be used to style parent dialogs differently when children are open.
data-nested '' Present when the dialog is a nested dialog, useful for hiding the overlay of nested dialogs to avoid overlapping with the root dialog's overlay.
CSS Variable Description Details
--bits-dialog-depth The nesting depth of the dialog (0 for root dialogs, 1 for first nested, etc.).
--bits-dialog-nested-count The number of currently open nested dialogs within this dialog. Updates reactively as nested dialogs open and close.

Dialog.Overlay

An overlay which covers the body when the dialog is open.

Property Type Description Details
forceMount boolean Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.Default: false
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type ChildSnippetProps = { open: boolean; props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-state enum - 'open' | 'closed' The state of the dialog.
data-starting-style '' Present during the initial open frame. Use this to define the starting styles for CSS transitions.
data-ending-style '' Present while closing before unmount. Use this to define the ending styles for CSS transitions.
data-dialog-overlay '' Present on the overlay.
data-nested-open '' Present when one or more nested dialogs are open within this dialog. Can be used to style parent dialogs differently when children are open.
data-nested '' Present when the dialog is a nested dialog, useful for hiding the overlay of nested dialogs to avoid overlapping with the root dialog's overlay.
CSS Variable Description Details
--bits-dialog-depth The nesting depth of the dialog (0 for root dialogs, 1 for first nested, etc.).
--bits-dialog-nested-count The number of currently open nested dialogs within this dialog. Updates reactively as nested dialogs open and close.

Dialog.Close

A button used to close the dialog.

Property Type Description Details
ref $bindable HTMLButtonElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-dialog-close '' Present on the close button.

Dialog.Title

An accessible title for the dialog.

Property Type Description Details
level union - 1 | 2 | 3 | 4 | 5 | 6 The heading level of the title.Default: 3
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-dialog-title '' Present on the title.

Dialog.Description

An accessible description for the dialog.

Property Type Description Details
ref $bindable HTMLDivElement The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null
children Snippet The children content to render.Default:  —— undefined
child Snippet - type SnippetProps = { props: Record<string, unknown>; }; Use render delegation to render your own element. See Child Snippet docs for more information.Default:  —— undefined
Data Attribute Value Description Details
data-dialog-description '' Present on the description.

더 알아보기 (Learn more)

Dialog는 다른 Bits UI 팝오버류 컴포넌트와 비슷하게 열림 상태, 포커스 트랩, 외부 상호작용 처리를 공유해요. 모달이 아니라 가벼운 안내나 확인이 필요한 상황이라면 Tooltip이나 Popover를, 드롭다운 형태의 메뉴가 필요하다면 Dropdown Menu 문서를 함께 비교해 보세요.