콤보박스(Combobox)
입력 필드와 드롭다운 옵션 목록의 기능을 결합한 컴포넌트예요. 사용자가 미리 정의된 선택지에서 검색하고, 필터링하고, 고를 수 있게 해줘요.
출처: 문서
본문
<script lang="ts">
import { Combobox } from "bits-ui";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import Check from "phosphor-svelte/lib/Check";
import OrangeSlice from "phosphor-svelte/lib/OrangeSlice";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
const fruits = [
{ value: "mango", label: "Mango" },
{ value: "watermelon", label: "Watermelon" },
{ value: "apple", label: "Apple" },
{ value: "pineapple", label: "Pineapple" },
{ value: "orange", label: "Orange" },
{ value: "grape", label: "Grape" },
{ value: "strawberry", label: "Strawberry" },
{ value: "banana", label: "Banana" },
{ value: "kiwi", label: "Kiwi" },
{ value: "peach", label: "Peach" },
{ value: "cherry", label: "Cherry" },
{ value: "blueberry", label: "Blueberry" },
{ value: "raspberry", label: "Raspberry" },
{ value: "blackberry", label: "Blackberry" },
{ value: "plum", label: "Plum" },
{ value: "apricot", label: "Apricot" },
{ value: "pear", label: "Pear" },
{ value: "grapefruit", label: "Grapefruit" }
];
let searchValue = $state("");
const filteredFruits = $derived(
searchValue === ""
? fruits
: fruits.filter((fruit) =>
fruit.label.toLowerCase().includes(searchValue.toLowerCase())
)
);
</script>
<Combobox.Root
type="multiple"
name="favoriteFruit"
onOpenChangeComplete={(o) => {
if (!o) searchValue = "";
}}
>
<div class="relative">
<OrangeSlice
class="text-muted-foreground absolute start-3 top-1/2 size-6 -translate-y-1/2"
/>
<Combobox.Input
oninput={(e) => (searchValue = e.currentTarget.value)}
class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-[296px] touch-none truncate border px-11 text-base transition-colors focus:ring-2 focus:ring-offset-2 sm:text-sm"
placeholder="Search a fruit"
aria-label="Search a fruit"
/>
<Combobox.Trigger
class="absolute end-3 top-1/2 size-6 -translate-y-1/2 touch-none"
>
<CaretUpDown class="text-muted-foreground size-6" />
</Combobox.Trigger>
</div>
<Combobox.Portal>
<Combobox.Content
class="focus-override border-muted 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 outline-hidden z-50 h-96 max-h-[var(--bits-combobox-content-available-height)] w-[var(--bits-combobox-anchor-width)] min-w-[var(--bits-combobox-anchor-width)] select-none rounded-xl border px-1 py-3 data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1"
sideOffset={10}
>
<Combobox.ScrollUpButton
class="flex w-full items-center justify-center py-1"
>
<CaretDoubleUp class="size-3" />
</Combobox.ScrollUpButton>
<Combobox.Viewport class="p-1">
{#each filteredFruits as fruit, i (i + fruit.value)}
<Combobox.Item
class="rounded-button data-highlighted:bg-muted outline-hidden flex h-10 w-full select-none items-center py-3 pl-5 pr-1.5 text-sm capitalize"
value={fruit.value}
label={fruit.label}
>
{#snippet children({ selected })}
{fruit.label}
{#if selected}
<div class="ml-auto">
<Check />
</div>
{/if}
{/snippet}
</Combobox.Item>
{:else}
<span class="block px-5 py-2 text-sm text-muted-foreground">
No results found, try again.
</span>
{/each}
</Combobox.Viewport>
<Combobox.ScrollDownButton
class="flex w-full items-center justify-center py-1"
>
<CaretDoubleDown class="size-3" />
</Combobox.ScrollDownButton>
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
개요(Overview)
Combobox 컴포넌트는 입력 필드와 선택 가능한 옵션의 드롭다운 목록 기능을 결합해요. 사용자가 미리 정의된 선택지 집합에서 검색, 필터링, 선택할 수 있게 해줘요.
주요 기능(Key Features)
- 키보드 내비게이션(Keyboard Navigation): 키보드 상호작용을 완전히 지원해서, 마우스 없이도 옵션을 탐색하고 선택할 수 있어요.
- 커스터마이징 가능한 렌더링(Customizable Rendering): 그룹화된 항목 지원을 포함해 옵션 렌더링을 위한 유연한 구조를 제공해요.
- 접근성(Accessibility): ARIA 속성과 키보드 상호작용으로 화면 낭독기 호환과 접근성 기준을 보장해요.
- 포털 지원(Portal Support): 드롭다운 콘텐츠를 포털에 렌더링해 복잡한 UI 구조에서 레이아웃 문제를 방지할 수 있어요.
구조(Architecture)
Combobox 컴포넌트는 각각의 역할이 분명한 여러 서브 컴포넌트로 구성돼요.
- Root: 콤보박스의 상태와 컨텍스트를 관리하는 메인 컨테이너 컴포넌트예요.
- Input: 사용자가 검색어를 입력할 수 있게 해주는 입력 필드예요.
- Trigger: 드롭다운 목록을 여는 버튼이나 요소예요.
- Portal: 드롭다운 콘텐츠를 body나 커스텀 타깃으로 포털링하는 역할을 해요.
- Group: 관련 항목을 묶는 데 쓰는 그룹 항목 컨테이너예요.
- GroupHeading: 항목 그룹의 제목으로, 그룹에 대한 설명 라벨을 제공해요.
- Item: 목록 안의 개별 항목이에요.
- Content: 항목을 표시하는 드롭다운 컨테이너예요. Floating UI를 사용해 트리거에 상대적으로 콘텐츠를 배치해요.
- ContentStatic: Content 컴포넌트의 대안으로, Floating UI를 쓰지 않고 콘텐츠 위치를 직접 정하고 싶을 때 사용해요.
- Viewport: 드롭다운 콘텐츠의 보이는 영역으로, 크기와 스크롤 동작을 결정하는 데 쓰여요.
- ScrollUpButton: 콘텐츠가 뷰포트보다 클 때 콘텐츠를 위로 스크롤하는 버튼이에요.
- ScrollDownButton: 콘텐츠가 뷰포트보다 클 때 콘텐츠를 아래로 스크롤하는 버튼이에요.
- Arrow:
Combobox.Content컴포넌트를 쓸 때 트리거를 가리키는 화살표 요소예요.
구조(Structure)
Combobox 컴포넌트가 코드에서 어떤 구조로 이루어져 있는지 한눈에 보여드릴게요.
<script lang="ts">
import { Combobox } from "bits-ui";
</script>
<Combobox.Root>
<Combobox.Input />
<Combobox.Trigger />
<Combobox.Portal>
<Combobox.Content>
<Combobox.Group>
<Combobox.GroupHeading />
<Combobox.Item />
</Combobox.Group>
<Combobox.Item />
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
재사용 컴포넌트(Reusable Components)
앱 전반에 걸쳐 재사용할 커스텀 콤보박스 컴포넌트를 만들 때는 Combobox 기본 요소를 활용하는 걸 권장해요.
CustomCombobox.svelte
<script lang="ts">
import { Combobox, type WithoutChildrenOrChild, mergeProps } from "bits-ui";
type Props = Combobox.RootProps & {
inputProps?: WithoutChildrenOrChild<Combobox.InputProps>;
contentProps?: WithoutChildrenOrChild<Combobox.ContentProps>;
};
let {
items = [],
value = $bindable(),
open = $bindable(false),
inputProps,
contentProps,
type,
...restProps
}: Props = $props();
let searchValue = $state("");
const filteredItems = $derived.by(() => {
if (searchValue === "") return items;
return items.filter((item) =>
item.label.toLowerCase().includes(searchValue.toLowerCase())
);
});
function handleInput(e: Event & { currentTarget: HTMLInputElement }) {
searchValue = e.currentTarget.value;
}
function handleOpenChange(newOpen: boolean) {
if (!newOpen) searchValue = "";
}
const mergedRootProps = $derived(
mergeProps(restProps, { onOpenChange: handleOpenChange })
);
const mergedInputProps = $derived(
mergeProps(inputProps, { oninput: handleInput })
);
</script>
<!--
Destructuring (required for bindable) and discriminated unions don't play well together,
so we cast the value to `never` to avoid type errors here. However, on the consumer
side, the component will still be type-checked correctly.
-->
<Combobox.Root
{type}
{items}
bind:value={value as never}
bind:open
{...mergedRootProps}
>
<Combobox.Input {...mergedInputProps} />
<Combobox.Trigger>Open</Combobox.Trigger>
<Combobox.Portal>
<Combobox.Content {...contentProps}>
{#each filteredItems as item, i (i + item.value)}
<Combobox.Item {...item}>
{#snippet children({ selected })}
{item.label}
{selected ? "✅" : ""}
{/snippet}
</Combobox.Item>
{:else}
<span> No results found </span>
{/each}
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
이제 +page.svelte에서 이렇게 사용할 수 있어요.
<script lang="ts">
import { CustomCombobox } from "$lib/components";
const items = [
{ value: "mango", label: "Mango" },
{ value: "watermelon", label: "Watermelon" },
{ value: "apple", label: "Apple" },
// ...
];
</script>
<CustomCombobox type="single" {items} />
value 상태 관리하기
이 절에서는 Combobox의 value 상태를 관리하는 방법을 다뤄요.
양방향 바인딩(Two-Way Binding)
bind:value를 사용하면 상태가 자동으로 동기화되어 아주 간단해요.
<script lang="ts">
import { Combobox } from "bits-ui";
let myValue = $state("");
</script>
<button onclick={() => (myValue = "A")}> Select A </button>
<Combobox.Root type="single" bind:value={myValue}>
<!-- ... -->
</Combobox.Root>
완전 제어(Fully Controlled)
함수 바인딩(Function Binding)을 사용하면 상태의 읽기와 쓰기를 완전히 제어할 수 있어요.
<script lang="ts">
import { Combobox } from "bits-ui";
let myValue = $state("");
function getValue() {
return myValue;
}
function setValue(newValue: string) {
myValue = newValue;
}
</script>
<Combobox.Root type="single" bind:value={getValue, setValue}>
<!-- ... -->
</Combobox.Root>
open 상태 관리하기
이 절에서는 Combobox의 open 상태를 관리하는 방법을 다뤄요.
양방향 바인딩(Two-Way Binding)
bind:open을 사용하면 상태가 자동으로 동기화되어 아주 간단해요.
<script lang="ts">
import { Combobox } from "bits-ui";
let myOpen = $state(false);
</script>
<button onclick={() => (myOpen = true)}> Open </button>
<Combobox.Root bind:open={myOpen}>
<!-- ... -->
</Combobox.Root>
완전 제어(Fully Controlled)
함수 바인딩(Function Binding)을 사용하면 상태의 읽기와 쓰기를 완전히 제어할 수 있어요.
<script lang="ts">
import { Combobox } from "bits-ui";
let myOpen = $state(false);
function getOpen() {
return myOpen;
}
function setOpen(newOpen: boolean) {
myOpen = newOpen;
}
</script>
<Combobox.Root type="single" bind:open={getOpen, setOpen}>
<!-- ... -->
</Combobox.Root>
Floating UI 사용하지 않기(Opt-out of Floating UI)
Combobox.Content 컴포넌트를 사용하면 Bits UI는 다른 팝오버류 컴포넌트처럼 Floating UI로 트리거에 상대적으로 콘텐츠를 배치해요.
이 동작을 쓰고 싶지 않다면 대신 Combobox.ContentStatic 컴포넌트를 사용할 수 있어요.
<Combobox.Root>
<Combobox.Trigger />
<Combobox.Input />
<Combobox.Portal>
<Combobox.ContentStatic>
<Combobox.ScrollUpButton />
<Combobox.Viewport>
<Combobox.Item />
<Combobox.Group>
<Combobox.GroupHeading />
<Combobox.Item />
</Combobox.Group>
</Combobox.Viewport>
<Combobox.ScrollDownButton />
</Combobox.ContentStatic>
</Combobox.Portal>
</Combobox.Root>
이 컴포넌트를 사용할 때는 콘텐츠 위치를 직접 정해야 해요. Combobox.Portal과 Combobox.ContentStatic을 함께 쓰면 예상치 못한 위치 지정 동작이 나올 수 있으니, 포털을 쓰지 않거나 우회하는 것도 고려하세요.
커스텀 앵커(Custom Anchor)
기본적으로 Combobox.Content는 Combobox.Input 컴포넌트에 고정(anchor)되어 콘텐츠가 놓일 위치가 결정돼요.
대신 다른 요소에 고정하고 싶다면 Combobox.Content 컴포넌트의 customAnchor prop에 셀렉터 문자열이나 HTMLElement를 전달할 수 있어요.
<script lang="ts">
import { Combobox } from "bits-ui";
let customAnchor = $state<HTMLElement>(null!);
</script>
<div bind:this={customAnchor}></div>
<Combobox.Root>
<Combobox.Trigger />
<Combobox.Input />
<Combobox.Content {customAnchor}>
<!-- ... -->
</Combobox.Content>
</Combobox.Root>
뷰포트가 뭔가요?(What is the Viewport?)
Combobox.Viewport 컴포넌트는 콘텐츠의 크기를 결정해서 위/아래 스크롤 버튼을 렌더링할지를 판단하는 데 쓰여요.
셀렉트 콘텐츠의 최소/최대 높이를 설정하고 싶다면 Combobox.Viewport 컴포넌트에 적용하면 돼요.
스크롤 업/다운 버튼(Scroll Up/Down Buttons)
Combobox.ScrollUpButton과 Combobox.ScrollDownButton 컴포넌트는 셀렉트 콘텐츠가 뷰포트보다 클 때 위/아래 스크롤 버튼을 렌더링하는 데 쓰여요.
스크롤 버튼을 쓸 때는 반드시 Combobox.Viewport 컴포넌트를 함께 사용해야 해요.
커스텀 스크롤 딜레이(Custom Scroll Delay)
버튼의 delay prop으로 초기 및 이후 스크롤 딜레이를 제어할 수 있어요.
예를 들어 Svelte의 cubicOut easing 함수를 사용하면 시간이 지날수록 빨라지는 부드러운 스크롤 효과를 만들 수 있어요.
코드 펼치기(Expand Code)
<script lang="ts">
import { Combobox } from "bits-ui";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import Check from "phosphor-svelte/lib/Check";
import OrangeSlice from "phosphor-svelte/lib/OrangeSlice";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
import { cubicOut } from "svelte/easing";
const fruits = [
{ value: "mango", label: "Mango" },
{ value: "watermelon", label: "Watermelon" },
{ value: "apple", label: "Apple" },
{ value: "pineapple", label: "Pineapple" },
{ value: "orange", label: "Orange" },
{ value: "grape", label: "Grape" },
{ value: "strawberry", label: "Strawberry" },
{ value: "banana", label: "Banana" },
{ value: "kiwi", label: "Kiwi" },
{ value: "peach", label: "Peach" },
{ value: "cherry", label: "Cherry" },
{ value: "blueberry", label: "Blueberry" },
{ value: "raspberry", label: "Raspberry" },
{ value: "blackberry", label: "Blackberry" },
{ value: "plum", label: "Plum" },
{ value: "apricot", label: "Apricot" },
{ value: "pear", label: "Pear" },
{ value: "grapefruit", label: "Grapefruit" }
];
// Duplicate the menu items a couple of times to show off scrolling a big list
const baseFruits = [...fruits];
for (let i = 0; i < 10; i++) {
for (let baseTheme of baseFruits) {
fruits.push({ ...baseTheme, value: baseTheme.value + i });
}
}
let searchValue = $state("");
const filteredFruits = $derived(
searchValue === ""
? fruits
: fruits.filter((fruit) =>
fruit.label.toLowerCase().includes(searchValue.toLowerCase())
)
);
function autoScrollDelay(tick: number) {
const maxDelay = 200;
const minDelay = 25;
const steps = 30;
const progress = Math.min(tick / steps, 1);
// Use the cubicOut easing function from svelte/easing
return maxDelay - (maxDelay - minDelay) * cubicOut(progress);
}
</script>
<Combobox.Root
type="multiple"
name="favoriteFruit"
onOpenChangeComplete={(o) => {
if (!o) searchValue = "";
}}
>
<div class="relative">
<OrangeSlice
class="text-muted-foreground absolute start-3 top-1/2 size-6 -translate-y-1/2"
/>
<Combobox.Input
oninput={(e) => (searchValue = e.currentTarget.value)}
class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-[296px] truncate border px-11 text-base transition-colors focus:ring-2 focus:ring-offset-2 sm:text-sm"
placeholder="Search a fruit"
aria-label="Search a fruit"
/>
<Combobox.Trigger class="absolute end-3 top-1/2 size-6 -translate-y-1/2">
<CaretUpDown class="text-muted-foreground size-6" />
</Combobox.Trigger>
</div>
<Combobox.Portal>
<Combobox.Content
class="focus-override border-muted 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 outline-hidden z-50 h-96 max-h-[var(--bits-combobox-content-available-height)] w-[var(--bits-combobox-anchor-width)] min-w-[var(--bits-combobox-anchor-width)] select-none rounded-xl border px-1 py-3 data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1"
sideOffset={10}
>
<Combobox.ScrollUpButton
class="flex w-full items-center justify-center py-1"
delay={autoScrollDelay}
>
<CaretDoubleUp class="size-3" />
</Combobox.ScrollUpButton>
<Combobox.Viewport class="p-1">
{#each filteredFruits as fruit, i (i + fruit.value)}
<Combobox.Item
class="rounded-button data-highlighted:bg-muted outline-hidden flex h-10 w-full select-none items-center py-3 pl-5 pr-1.5 text-sm capitalize"
value={fruit.value}
label={fruit.label}
>
{#snippet children({ selected })}
{fruit.label}
{#if selected}
<div class="ml-auto">
<Check />
</div>
{/if}
{/snippet}
</Combobox.Item>
{:else}
<span class="block px-5 py-2 text-sm text-muted-foreground">
No results found, try again.
</span>
{/each}
</Combobox.Viewport>
<Combobox.ScrollDownButton
class="flex w-full items-center justify-center py-1"
delay={autoScrollDelay}
>
<CaretDoubleDown class="size-3" />
</Combobox.ScrollDownButton>
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
네이티브 스크롤/오버플로(Native Scrolling/Overflow)
스크롤 버튼을 쓰지 않고 표준 스크롤바/오버플로 동작을 선호한다면 Combobox.Scroll[Up|Down]Button 컴포넌트와 Combobox.Viewport 컴포넌트를 생략하면 돼요.
스크롤을 활성화하려면 Combobox.Content 컴포넌트에 높이를 설정하고 적절한 overflow 스타일을 적용해야 해요.
스크롤 잠금(Scroll Lock)
열려 있을 때 사용자가 Combobox.Content 컴포넌트 바깥으로 스크롤하지 못하게 하려면 preventScroll prop을 true로 설정할 수 있어요.
<Combobox.Content preventScroll={true}>
<!-- ... -->
</Combobox.Content>
하이라이트 항목(Highlighted Items)
Combobox 컴포넌트는 항목 하이라이트에 WAI-ARIA descendant 패턴을 따라요. 즉 키보드로 탐색할 때도 Combobox.Input에 포커스가 계속 유지되고, 사용자가 탐색하면서 항목이 하이라이트돼요.
하이라이트 항목 스타일링
Combobox.Item 컴포넌트의 data-highlighted 속성을 사용해 하이라이트될 때 항목을 다르게 스타일링할 수 있어요.
onHighlight / onUnhighlight
항목이 하이라이트되거나 해제될 때 부수 효과를 발생시키려면 onHighlight와 onUnhighlight prop을 사용할 수 있어요.
<Combobox.Item onHighlight={() => console.log('I am highlighted!')} onUnhighlight={() => console.log('I am unhighlighted!')} />
<!-- ... -->
</Combobox.Item>
Svelte 트랜지션(Svelte Transitions)
forceMount prop과 child 스니펫을 함께 사용하면 Combobox.Content 컴포넌트를 강제로 마운트해서 Svelte 트랜지션 또는 더 많은 제어가 필요한 다른 애니메이션 라이브러리를 쓸 수 있어요.
<script lang="ts">
import { Combobox } from "bits-ui";
import { fly } from "svelte/transition";
</script>
<Combobox.Content forceMount>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:fly>
<!-- ... -->
</div>
</div>
{/if}
{/snippet}
</Combobox.Content>
물론 이건 가장 예쁜 문법은 아니에요. 이 방식을 쓸 거라면 이 로직을 처리하는 재사용 콘텐츠 컴포넌트를 직접 만드는 걸 권장해요. Bits UI 컴포넌트에서 트랜지션을 사용하는 방법에 대한 자세한 내용은 Transitions 문서를 참고하세요.
코드 펼치기(Expand Code)
<script lang="ts">
import { Combobox } from "bits-ui";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import Check from "phosphor-svelte/lib/Check";
import OrangeSlice from "phosphor-svelte/lib/OrangeSlice";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
import { fly } from "svelte/transition";
const fruits = [
{ value: "mango", label: "Mango" },
{ value: "watermelon", label: "Watermelon" },
{ value: "apple", label: "Apple" },
{ value: "pineapple", label: "Pineapple" },
{ value: "orange", label: "Orange" },
{ value: "grape", label: "Grape" },
{ value: "strawberry", label: "Strawberry" },
{ value: "banana", label: "Banana" },
{ value: "kiwi", label: "Kiwi" },
{ value: "peach", label: "Peach" },
{ value: "cherry", label: "Cherry" },
{ value: "blueberry", label: "Blueberry" },
{ value: "raspberry", label: "Raspberry" },
{ value: "blackberry", label: "Blackberry" },
{ value: "plum", label: "Plum" },
{ value: "apricot", label: "Apricot" },
{ value: "pear", label: "Pear" },
{ value: "grapefruit", label: "Grapefruit" }
];
let searchValue = $state("");
const filteredFruits = $derived(
searchValue === ""
? fruits
: fruits.filter((fruit) =>
fruit.label.toLowerCase().includes(searchValue.toLowerCase())
)
);
</script>
<Combobox.Root
type="single"
name="favoriteFruit"
onOpenChangeComplete={(o) => {
if (!o) searchValue = "";
}}
>
<div class="relative">
<OrangeSlice
class="text-muted-foreground absolute start-3 top-1/2 size-6 -translate-y-1/2"
/>
<Combobox.Input
oninput={(e) => (searchValue = e.currentTarget.value)}
class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 focus:ring-foreground focus:ring-offset-background focus:outline-hidden inline-flex w-[296px] truncate border px-11 text-base transition-colors focus:ring-2 focus:ring-offset-2 sm:text-sm"
placeholder="Search a fruit"
aria-label="Search a fruit"
/>
<Combobox.Trigger class="absolute end-3 top-1/2 size-6 -translate-y-1/2">
<CaretUpDown class="text-muted-foreground size-6" />
</Combobox.Trigger>
</div>
<Combobox.Portal>
<Combobox.Content
class="border-muted bg-background shadow-popover outline-hidden h-96 max-h-[var(--bits-combobox-content-available-height)] w-[var(--bits-combobox-anchor-width)] min-w-[var(--bits-combobox-anchor-width)] rounded-xl border px-1 py-3"
sideOffset={10}
forceMount
>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:fly={{ duration: 300 }}>
<Combobox.ScrollUpButton
class="flex w-full items-center justify-center"
>
<CaretDoubleUp class="size-3" />
</Combobox.ScrollUpButton>
<Combobox.Viewport class="p-1">
{#each filteredFruits as fruit, i (i + fruit.value)}
<Combobox.Item
class="rounded-button data-highlighted:bg-muted outline-hidden flex h-10 w-full select-none items-center py-3 pl-5 pr-1.5 text-sm capitalize"
value={fruit.value}
label={fruit.label}
>
{#snippet children({ selected })}
{fruit.label}
{#if selected}
<div class="ml-auto">
<Check />
</div>
{/if}
{/snippet}
</Combobox.Item>
{:else}
<span class="block px-5 py-2 text-sm text-muted-foreground">
No results found, try again.
</span>
{/each}
</Combobox.Viewport>
<Combobox.ScrollDownButton
class="flex w-full items-center justify-center"
>
<CaretDoubleDown class="size-3" />
</Combobox.ScrollDownButton>
</div>
</div>
{/if}
{/snippet}
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
API 참조(API Reference)
Combobox.Root
콤보박스의 상태를 관리하고 범위를 지정하는 루트 콤보박스 컴포넌트예요.
| Property | Type | Description | Details |
|---|---|---|---|
type required |
enum - 'single' | 'multiple' |
The type of combobox.Default: —— undefined |
|
value $bindable |
union - string | string[] |
The value of the combobox. When the type is 'single', this should be a string. When the type is 'multiple', this should be an array of strings.Default: —— undefined |
|
onValueChange |
function - (string) => void | (string[]) => void |
A callback that is fired when the combobox value changes. When the type is 'single', the argument will be a string. When the type is 'multiple', the argument will be an array of strings.Default: —— undefined |
|
open $bindable |
boolean |
The open state of the combobox menu.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 combobox component is disabled.Default: false |
|
name |
string |
The name to apply to the hidden input element for form submission. If provided, a hidden input element will be rendered to submit the value of the combobox.Default: —— undefined |
|
required |
boolean |
Whether or not the combobox menu is required.Default: false |
|
scrollAlignment |
enum - 'nearest' | 'center' |
The alignment of the highlighted item when scrolling.Default: ''nearest'' |
|
loop |
boolean |
Whether or not the combobox menu should loop through items.Default: false |
|
allowDeselect |
boolean |
Whether or not the user can deselect the selected item by pressing it in a single select.Default: true |
|
items |
Item[] - { value: string; label: string; disabled?: boolean}[] |
Optionally provide an array of objects representing the items in the select for autofill capabilities. Only applicable to combobox's with type single``Default: —— undefined |
|
inputValue |
string |
A read-only value that controls the text displayed in the combobox input. Use this to programmatically update the input value when the selection changes outside the component, ensuring the displayed text stays in sync with the actual value.Default: —— undefined |
|
children |
Snippet |
The children content to render.Default: —— undefined |
Combobox.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 combobox's open state. | |
data-disabled |
'' |
Present when the combobox is disabled. | |
data-combobox-trigger |
'' |
Present on the trigger element. |
Combobox.Viewport
스크롤 업/다운 버튼 렌더링을 위해 콤보박스의 스크롤 위치를 추적하는 선택적 요소예요.
| 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-combobox-viewport |
'' |
Present on the viewport element. |
Combobox.Content
콤보박스의 항목을 담고 있는 요소예요.
| Property | Type | Description | Details |
|---|---|---|---|
side |
enum - 'top' | 'bottom' | 'left' | 'right' |
The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.Default: 'bottom' |
|
sideOffset |
number |
The distance in pixels from the anchor to the floating element.Default: 0 |
|
align |
enum - 'start' | 'center' | 'end' |
The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.Default: 'start' |
|
alignOffset |
number |
The distance in pixels from the anchor to the floating element.Default: 0 |
|
arrowPadding |
number |
The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.Default: 0 |
|
avoidCollisions |
boolean |
When true, overrides the side and align options to prevent collisions with the boundary edges.Default: true |
|
collisionBoundary |
union - Element | null |
A boundary element or array of elements to check for collisions against.Default: —— undefined |
|
collisionPadding |
union - number | Partial<Record<Side, number>> |
The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.Default: 0 |
|
sticky |
enum - 'partial' | 'always' |
The sticky behavior on the align axis. 'partial' will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst 'always' will keep the content in the boundary regardless.Default: 'partial' |
|
hideWhenDetached |
boolean |
When true, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.Default: true |
|
updatePositionStrategy |
enum - 'optimized' | 'always' |
The strategy to use when updating the position of the content. When 'optimized' the content will only be repositioned when the trigger is in the viewport. When 'always' the content will be repositioned whenever the position changes.Default: 'optimized' |
|
strategy |
enum - 'fixed' | 'absolute' |
The positioning strategy to use for the floating element. When 'fixed' the element will be positioned relative to the viewport. When 'absolute' the element will be positioned relative to the nearest positioned ancestor.Default: 'fixed' |
|
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: false |
|
customAnchor |
union - string | HTMLElement | Measurable | null |
Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.Default: null |
|
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' |
|
preventOverflowTextSelection |
boolean |
When true, prevents the text selection from overflowing the bounds of the element.Default: true |
|
dir |
enum - 'ltr' | 'rtl' |
The reading direction of the app.Default: 'ltr' |
|
loop |
boolean |
Whether or not the combobox should loop through items when reaching the end.Default: false |
|
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 = { /** * Props for the positioning wrapper * Do not style this element - * styling should be applied to the content element */ wrapperProps: Record<string, unknown>; /** * Props for your content element * Apply your custom styles here */ props: Record<string, unknown>; /** * Content visibility state * Use this for conditional rendering with * Svelte transitions */ open: boolean; }; |
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 combobox's open state. | |
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-combobox-content |
'' |
Present on the content element. |
| CSS Variable | Description | Details |
|---|---|---|
--bits-combobox-content-transform-origin |
The transform origin of the content element. | |
--bits-combobox-content-available-width |
The available width of the content element. | |
--bits-combobox-content-available-height |
The available height of the content element. | |
--bits-combobox-anchor-width |
The width of the anchor element. | |
--bits-combobox-anchor-height |
The height of the anchor element. |
Combobox.ContentStatic
콤보박스의 항목을 담고 있는 요소예요. (정적/Floting UI 없음)
| 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 |
|
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 |
|
preventOverflowTextSelection |
boolean |
When true, prevents the text selection from overflowing the bounds of the element.Default: true |
|
dir |
enum - 'ltr' | 'rtl' |
The reading direction of the app.Default: 'ltr' |
|
loop |
boolean |
Whether or not the combobox should loop through items when reaching the end.Default: false |
|
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 combobox's open state. | |
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-combobox-content |
'' |
Present on the content element. |
Combobox.Portal
사용하면 열려 있을 때 콤보박스 콘텐츠를 body나 커스텀 to 요소에 렌더링해요.
| 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 |
Combobox.Item
Combobox.Content 컴포넌트의 자식이어야 하는 콤보박스 항목이에요.
| Property | Type | Description | Details |
|---|---|---|---|
value required |
string |
The value of the item.Default: —— undefined |
|
label |
string |
The label of the item, which is what the list will be filtered by.Default: —— undefined |
|
disabled |
boolean |
Whether or not the combobox item is disabled. This will prevent interaction/selection.Default: false |
|
onHighlight |
function - () => void |
A callback that is fired when the item is highlighted.Default: —— undefined |
|
onUnhighlight |
function - () => void |
A callback that is fired when the item is unhighlighted.Default: —— undefined |
|
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-value |
string |
The value of the combobox item. | |
data-label |
string |
The label of the combobox item. | |
data-disabled |
'' |
Present when the item is disabled. | |
data-highlighted |
'' |
Present when the item is highlighted, which is either via keyboard navigation of the menu or hover. | |
data-selected |
'' |
Present when the item is selected. | |
data-combobox-item |
'' |
Present on the item element. |
Combobox.Input
보통 콘텐츠에 표시되는 콤보박스 입력 요소의 표현이에요.
| Property | Type | Description | Details |
|---|---|---|---|
defaultValue |
string |
The default value of the input. This is not a reactive prop and is only used to populate the input when the combobox is first mounted if there is already a value set.Default: —— undefined |
|
clearOnDeselect |
boolean |
Whether to clear the input when the last item is deselected.Default: false |
|
ref $bindable |
HTMLInputElement |
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 combobox's open state. | |
data-disabled |
'' |
Present when the combobox is disabled. | |
data-combobox-input |
'' |
Present on the input element. |
Combobox.Group
관련된 콤보박스 항목들의 그룹이에요.
| 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-combobox-group |
'' |
Present on the group element. |
Combobox.GroupHeading
부모 콤보박스 그룹의 제목이에요. 관련 콤보박스 항목들의 그룹을 설명하는 데 쓰여요.
| 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-combobox-group-heading |
'' |
Present on the group heading element. |
Combobox.ScrollUpButton
콤보박스 안의 스크롤 경험을 개선하기 위한 선택적 위쪽 스크롤 버튼 요소예요. Combobox.Viewport 컴포넌트와 함께 사용해야 해요.
| Property | Type | Description | Details |
|---|---|---|---|
delay |
function - (tick: number) => number |
Controls the initial delay (tick 0) and delay between auto-scrolls in milliseconds.Default: () => 50 |
|
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-combobox-scroll-up-button |
'' |
Present on the scroll up button element. |
Combobox.ScrollDownButton
콤보박스 안의 스크롤 경험을 개선하기 위한 선택적 아래쪽 스크롤 버튼 요소예요. Combobox.Viewport 컴포넌트와 함께 사용해야 해요.
| Property | Type | Description | Details |
|---|---|---|---|
delay |
function - (tick: number) => number |
Controls the initial delay (tick 0) and delay between auto-scrolls in milliseconds.Default: () => 50 |
|
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-combobox-scroll-down-button |
'' |
Present on the scroll down button element. |
Combobox.Arrow
열려 있을 때 콘텐츠를 가리키는 선택적 화살표 요소예요.
| Property | Type | Description | Details |
|---|---|---|---|
width |
number |
The width of the arrow in pixels.Default: 8 |
|
height |
number |
The height of the arrow in pixels.Default: 8 |
|
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-arrow |
'' |
Present on the arrow element. |
더 알아보기 (Learn more)
검색과 필터링이 핵심이라면 커맨드(Command) 컴포넌트가 콤보박스와 비슷하면서 다른 느낌의 대안이 될 수 있어요. 드롭다운 위치 지정과 트랜지션을 더 다루고 싶다면 Transitions 문서를 참고하세요.