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

접이식(Collapsible)

원문 보기 위키 갱신

콘텐츠 섹션을 접었다 펼쳤다 하면서 화면 공간을 효율적으로 관리하고 싶을 때 쓰는 컴포넌트예요. 사용자가 필요할 때 내용을 보여주거나 숨길 수 있게 해줘요.

출처: 문서

본문

<script lang="ts">
  import { Collapsible } from "bits-ui";
  import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
</script>
<Collapsible.Root class="w-[327px] space-y-3">
  <div class="flex items-center justify-between space-x-10">
    <h4 class="text-[15px] font-medium">@huntabyte starred 3 repositories</h4>
    <Collapsible.Trigger
      class="rounded-9px border-border-input bg-background-alt text-foreground shadow-btn hover:bg-muted inline-flex h-10 w-10 items-center justify-center border transition-all active:scale-[0.98]"
      aria-label="Show starred repositories"
    >
      <CaretUpDown class="size-4" weight="bold" />
    </Collapsible.Trigger>
  </div>
  <Collapsible.Content
    hiddenUntilFound
    class="data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up space-y-2 overflow-hidden font-mono text-[15px] tracking-[0.01em]"
  >
    <div
      class="rounded-9px bg-muted inline-flex h-12 w-full items-center px-[18px] py-3"
    >
      @huntabyte/bits-ui
    </div>
    <div
      class="rounded-9px bg-muted inline-flex h-12 w-full items-center px-[18px] py-3"
    >
      @huntabyte/shadcn-svelte
    </div>
    <div
      class="rounded-9px bg-muted inline-flex h-12 w-full items-center px-[18px] py-3"
    >
      @svecosystem/runed
    </div>
  </Collapsible.Content>
</Collapsible.Root>

개요(Overview)

Collapsible 컴포넌트는 펼치거나 접을 수 있는 콘텐츠 섹션을 만들 수 있게 해줘요. UI에서 공간을 효율적으로 관리하고 정보를 정리하는 방법을 제공해서, 사용자가 필요에 따라 콘텐츠를 보여주거나 숨길 수 있게 해요.

주요 기능(Key Features)

  • 접근성(Accessibility): 화면 낭독기 호환을 위한 ARIA 속성과 키보드 내비게이션을 지원해요.
  • 트랜지션 지원(Transition Support): 상태 간 부드러운 전환을 위한 CSS 변수와 데이터 속성을 제공해요.
  • 유연한 상태 관리(Flexible State Management): 제어와 비제어 상태를 모두 지원해서 필요할 때 직접 제어할 수 있어요.
  • 복합 컴포넌트 구조(Compound Component Structure): 함께 동작하는 서브 컴포넌트 집합을 제공해 풍부한 기능을 갖춘 콜랩시블을 만들 수 있어요.
  • 찾을 때까지 숨김(Hidden Until Found): 브라우저 검색과 연동되는 hidden="until-found" 속성을 지원해요.

구조(Architecture)

Collapsible 컴포넌트는 각각의 역할이 분명한 몇 개의 서브 컴포넌트로 구성돼요.

  • Root: 콜랩시블 기능의 상태와 컨텍스트를 관리하는 부모 컨테이너예요.
  • Trigger: 콘텐츠의 펼침/접힘 상태를 토글하는 상호작용 요소(예: 버튼)예요.
  • Content: 콜랩시블 상태에 따라 보이거나 숨겨지는 콘텐츠를 담는 컨테이너예요.

구조(Structure)

Collapsible 컴포넌트가 코드에서 어떤 구조로 이루어져 있는지 한눈에 보여드릴게요.

<script lang="ts">
  import { Collapsible } from "bits-ui";
</script>
<Collapsible.Root>
  <Collapsible.Trigger />
  <Collapsible.Content />
</Collapsible.Root>

재사용 컴포넌트(Reusable Components)

앱 전반에 걸쳐 사용할 나만의 커스텀 콜랩시블 컴포넌트를 만들 때는 Collapsible 기본 요소를 활용하는 걸 권장해요.

MyCollapsible.svelte

<script lang="ts">
  import { Collapsible, type WithoutChild } from "bits-ui";
  type Props = WithoutChild<Collapsible.RootProps> & {
    buttonText: string;
  };
  let {
    open = $bindable(false),
    ref = $bindable(null),
    buttonText,
    children,
    ...restProps
  }: Props = $props();
</script>
<Collapsible.Root bind:open bind:ref {...restProps}>
  <Collapsible.Trigger>{buttonText}</Collapsible.Trigger>
  <Collapsible.Content>
    {@render children?.()}
  </Collapsible.Content>
</Collapsible.Root>

그러면 앱에서 MyCollapsible 컴포넌트를 이렇게 사용할 수 있어요.

+page.svelte

<script lang="ts">
  import MyCollapsible from "$lib/components/MyCollapsible.svelte";
</script>
<MyCollapsible buttonText="Open Collapsible"
  >Here is my collapsible content.</MyCollapsible
>

open 상태 관리하기

이 절에서는 Collapsible의 open 상태를 관리하는 방법을 다뤄요.

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

bind:open을 사용하면 상태가 자동으로 동기화되어 아주 간단해요.

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

완전 제어(Fully Controlled)

함수 바인딩(Function Binding)을 사용하면 상태를 완전히 제어할 수 있어요.

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

Svelte 트랜지션(Svelte Transitions)

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

forceMount와 child 스니펫 사용하기

Collapsible 컴포넌트에 Svelte 트랜지션을 적용하려면 child 스니펫과 함께 forceMount prop을 사용해요. 이 방법으로 Collapsible.Content의 마운트 동작과 애니메이션을 완전히 제어할 수 있어요.

<script lang="ts">
  import { Collapsible } from "bits-ui";
  import { fade } from "svelte/transition";
</script>
<Collapsible.Root>
  <Collapsible.Trigger>Open</Collapsible.Trigger>
  <Collapsible.Content forceMount>
    {#snippet child({ props, open })}
      {#if open}
        <div {...props} transition:fade>
          <!-- ... -->
        </div>
      {/if}
    {/snippet}
  </Collapsible.Content>
</Collapsible.Root>

이 예시에서:

  • forceMount prop이 콘텐츠가 항상 DOM에 있도록 보장해요.
  • child 스니펫이 열림 상태와 컴포넌트 prop에 접근할 수 있게 해줘요.
  • Svelte의 #if 블록이 콘텐츠가 보일 시점을 제어해요.
  • transition:fade 지시문이 애니메이션을 적용해요.

모범 사례(Best Practices)

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

MyCollapsibleContent.svelte

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

그러면 앱 곳곳에서 MyCollapsibleContent 컴포넌트를 다른 Collapsible 기본 요소들과 함께 사용할 수 있어요.

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

찾을 때까지 숨김(Hidden Until Found)

hiddenUntilFound prop은 브라우저의 페이지 내 검색(find-in-page) 기능과 연동돼요. 활성화하면 콜랩시블 콘텐츠에 hidden="until-found"가 표시되어, 사용자가 그 안의 텍스트를 검색하면 브라우저가 접혀 있던 콘텐츠를 자동으로 펼쳐줘요.

코드 펼치기(Expand Code)

<script lang="ts">
  import { Collapsible } from "bits-ui";
  import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
</script>
<div class="flex w-full max-w-md flex-col gap-4">
  <div
    class="border-border bg-background-alt absolute left-4 top-4 flex flex-col gap-2 rounded-xl border p-4"
  >
    <div class="text-foreground-alt flex flex-col gap-2 text-sm">
      <span>Try searching for "searchable content" on this page</span>
      <code class="bg-muted w-fit rounded px-1 py-0.5 text-xs"
        >(Ctrl+F / Cmd+F)</code
      >
    </div>
  </div>
  <Collapsible.Root class="flex flex-col gap-3">
    <div class="flex items-center justify-between gap-4">
      <h4 class="text-[15px] font-medium">FAQ: How does search work?</h4>
      <Collapsible.Trigger
        class="rounded-9px border-border-input bg-background-alt text-foreground shadow-btn hover:bg-muted inline-flex h-10 w-10 items-center justify-center border transition-all active:scale-[0.98]"
        aria-label="Toggle FAQ answer"
      >
        <CaretUpDown class="size-4" weight="bold" />
      </Collapsible.Trigger>
    </div>
    <Collapsible.Content
      hiddenUntilFound
      class="data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up overflow-hidden"
    >
      <div
        class="bg-background border-border rounded-lg border p-4 text-[14px] leading-relaxed"
      >
        <p class="mb-3">
          This collapsible contains <strong>searchable content</strong> that
          demonstrates the
          <code class="bg-muted rounded px-1 py-0.5 text-xs"
            >hiddenUntilFound</code
          > feature. When you search for text within this collapsed section, the
          browser will automatically expand it to show the matching results.
        </p>
      </div>
    </Collapsible.Content>
  </Collapsible.Root>
</div>

기본 사용법(Basic Usage)

<script lang="ts">
  import { Collapsible } from "bits-ui";
</script>
<Collapsible.Root>
  <Collapsible.Trigger>Show More Details</Collapsible.Trigger>
  <Collapsible.Content hiddenUntilFound={true}>
    <p>
      This content will be automatically revealed when users search for text
      within it using Ctrl+F (Cmd+F on Mac).
    </p>
    <p>
      For example, try searching for "automatically revealed" on this page.
    </p>
  </Collapsible.Content>
</Collapsible.Root>

API 참조(API Reference)

Collapsible.Root

콜랩시블의 상태를 관리하는 루트 컨테이너예요.

Property Type Description Details
open $bindable boolean The open state of the collapsible. The content will be visible when this is true, and hidden when it's false.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
disabled boolean Whether or not the collapsible is disabled. This prevents the user from interacting with it.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 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-state enum - 'open' | 'closed' The collapsible's open state.
data-disabled '' Present when the collapsible is disabled.
data-collapsible-root '' Present on the root element.

Collapsible.Trigger

콜랩시블의 열림 상태를 토글하는 버튼이에요.

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-state enum - 'open' | 'closed' The collapsible's open state.
data-disabled '' Present when the collapsible or this trigger is disabled.
data-collapsible-trigger '' Present on the trigger element.

Collapsible.Content

콜랩시블이 열려 있을 때 표시되는 콘텐츠예요.

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
hiddenUntilFound boolean When true, the content will be marked with hidden="until-found" when collapsed, allowing browsers to find and automatically expand the content during page searches.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 SnippetProps = { 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 collapsible's open state.
data-disabled '' Present when the collapsible is disabled.
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-collapsible-content '' Present on the content element.
CSS Variable Description Details
--bits-collapsible-content-height The height of the collapsible content element.
--bits-collapsible-content-width The width of the collapsible content element.

더 알아보기 (Learn more)

여러 섹션을 탭이나 아코디언처럼 접었다 펼칠 수 있게 만들고 싶다면 아코디언(Accordion) 컴포넌트를 살펴보세요. 트랜지션을 커스터마이즈하고 싶다면 Transitions 문서를 참고하면 좋아요.