Select 문서
Select는 사용자가 옵션 목록에서 하나 또는 여러 개를 고를 수 있게 해 주는 컴포넌트예요. 타입어헤드 검색, 키보드 내비게이션, 항목 그룹화 등 기본 <select>보다 훨씬 풍부한 선택 경험을 제공해요. 폼에서 미리 정의된 여러 옵션 중에서 골라야 할 때 유용해요.
출처: 문서
본문
아래 예시는 Select를 구성하는 기본 구조예요. Select.Root가 상태를 관리하고, 트리거와 콘텐츠, 항목들이 함께 선택 흐름을 만들어요.
<script lang="ts">
import { Select } from "bits-ui";
import Check from "phosphor-svelte/lib/Check";
import Palette from "phosphor-svelte/lib/Palette";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
const themes = [
{ value: "light-monochrome", label: "Light Monochrome" },
{ value: "dark-green", label: "Dark Green" },
{ value: "svelte-orange", label: "Svelte Orange" },
{ value: "punk-pink", label: "Punk Pink" },
{ value: "ocean-blue", label: "Ocean Blue", disabled: true },
{ value: "sunset-orange", label: "Sunset Orange" },
{ value: "sunset-red", label: "Sunset Red" },
{ value: "forest-green", label: "Forest Green" },
{ value: "lavender-purple", label: "Lavender Purple", disabled: true },
{ value: "mustard-yellow", label: "Mustard Yellow" },
{ value: "slate-gray", label: "Slate Gray" },
{ value: "neon-green", label: "Neon Green" },
{ value: "coral-reef", label: "Coral Reef" },
{ value: "midnight-blue", label: "Midnight Blue" },
{ value: "crimson-red", label: "Crimson Red" },
{ value: "mint-green", label: "Mint Green" },
{ value: "pastel-pink", label: "Pastel Pink" },
{ value: "golden-yellow", label: "Golden Yellow" },
{ value: "deep-purple", label: "Deep Purple" },
{ value: "turquoise-blue", label: "Turquoise Blue" },
{ value: "burnt-orange", label: "Burnt Orange" }
];
</script>
<Select.Root type="single" items={themes} allowDeselect={true}>
<Select.Trigger
class="h-input rounded-9px border-border-input bg-background data-placeholder:text-foreground-alt/50 inline-flex w-[296px] touch-none select-none items-center border px-[11px] text-sm transition-colors"
aria-label="Select a theme"
>
<Palette class="text-muted-foreground mr-[9px] size-6" />
<Select.Value placeholder="Select a theme" />
<CaretUpDown class="text-muted-foreground ml-auto size-6" />
</Select.Trigger>
<Select.Portal>
<Select.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-select-content-available-height)] w-[var(--bits-select-anchor-width)] min-w-[var(--bits-select-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}
>
<Select.ScrollUpButton class="flex w-full items-center justify-center">
<CaretDoubleUp class="size-3" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each themes as theme, i (i + theme.value)}
<Select.Item
class="rounded-button data-highlighted:bg-muted outline-hidden data-disabled:opacity-50 flex h-10 w-full select-none items-center py-3 pl-5 pr-1.5 text-sm capitalize"
value={theme.value}
label={theme.label}
disabled={theme.disabled}
>
{#snippet children({ selected })}
{theme.label}
{#if selected}
<div class="ml-auto">
<Check aria-label="check" />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton class="flex w-full items-center justify-center">
<CaretDoubleDown class="size-3" />
</Select.ScrollDownButton>
</Select.Content>
</Select.Portal>
</Select.Root>
개요 (Overview)
Select 컴포넌트는 선택 가능한 옵션 목록을 사용자에게 제공해요. 타입어헤드(typeahead) 검색, 키보드 내비게이션, 그룹화 등 선택 경험을 한층 향상시켜 주는 기능들이 내장되어 있어요. 미리 정의된 옵션 집합에서 고르는 상황에 특히 유용하며, 기본 <select> 요소보다 훨씬 풍부한 기능을 제공해요.
주요 기능 (Key Features)
- 타입어헤드 검색: 사용자가 입력하는 대로 빠르게 옵션을 찾을 수 있어요
- 키보드 내비게이션: 키보드 상호작용을 완전히 지원해서, 화살표 키로 이동하고 Enter로 선택하는 등 다양한 조작이 가능해요.
- 그룹화된 옵션: 옵션을 논리적인 그룹으로 묶어서, 많은 옵션 목록의 가독성과 정돈도를 높일 수 있어요.
- 스크롤 관리: 긴 목록을 쉽게 탐색하도록 위/아래 스크롤 버튼을 제공해요.
- 접근성: ARIA 속성과 키보드 지원이 내장되어 있어서 화면 낭독기와의 호환성 및 접근성 표준 준수를 보장해요.
- 포털 지원: 선택 콘텐츠를 포털로 렌더링하는 옵션을 제공해서, 복잡한 UI 구조에서 레이아웃 문제를 막아 줘요.
구조 (Architecture)
Select 컴포넌트는 각기 특정 역할을 담당하는 여러 하위 컴포넌트로 구성돼요:
- Root: 콤보박스의 상태와 컨텍스트를 관리하는 메인 컨테이너 컴포넌트예요.
- Trigger: 드롭다운 목록을 여는 버튼 또는 요소예요.
- Portal: 드롭다운 콘텐츠를 body나 커스텀 대상으로 포털링(potaling)하는 역할을 해요.
- Group: 관련 항목들을 묶는 데 쓰는 그룹 항목 컨테이너예요.
- GroupHeading: 항목 그룹의 제목으로, 그룹을 설명하는 라벨을 제공해요.
- Item: 목록 안의 개별 항목이에요.
- Content: 항목들을 표시하는 드롭다운 컨테이너예요. Floating UI를 사용해 트리거 기준으로 콘텐츠를 배치해요.
- ContentStatic (선택 사항): Content 컴포넌트의 대안으로, Floating UI를 쓰지 않고 콘텐츠 위치를 직접 정하고 싶을 때 사용해요.
- Viewport: 드롭다운 콘텐츠의 보이는 영역으로, 크기와 스크롤 동작을 결정하는 데 사용돼요.
- ScrollUpButton: 콘텐츠가 뷰포트보다 클 때 콘텐츠를 위로 스크롤하는 버튼이에요.
- ScrollDownButton: 콘텐츠가 뷰포트보다 클 때 콘텐츠를 아래로 스크롤하는 버튼이에요.
- Arrow:
Combobox.Content컴포넌트를 사용할 때 트리거를 가리키는 화살표 요소예요.
구조 (Structure)
Select 컴포넌트가 코드에서 어떻게 구성되는지 한눈에 보여 드릴게요:
<script lang="ts">
import { Select } from "bits-ui";
</script>
<Select.Root>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Portal>
<Select.Content>
<Select.ScrollUpButton />
<Select.Viewport>
<Select.Item />
<Select.Group>
<Select.GroupHeading />
<Select.Item />
</Select.Group>
<Select.ScrollDownButton />
</Select.Viewport>
</Select.Content>
</Select.Portal>
</Select.Root>
재사용 가능한 컴포넌트 (Reusable Components)
위 구조에서 보듯이 Select 컴포넌트는 여러 조각으로 이루어져 있어요. 이 조각들은 최대한의 유연성과 커스터마이즈 옵션을 제공하기 위해 마련된 것이지만, 애플리케이션 곳곳에서 select를 쓸 때마다 전부 작성하는 건 꽤 번거로운 일이에요.
이런 번거로움을 줄이려면, 기본 요소들을 감싸면서 여러분의 사용 사례에 더 편리한 API를 제공하는 재사용 가능한 select 컴포넌트를 직접 만드는 걸 권장해요.
옵션 목록을 받아 각각을 항목으로 렌더링하는 재사용 가능한 MySelect 컴포넌트를 만드는 예시를 살펴볼게요.
MySelect.svelte
<script lang="ts">
import { Select, type WithoutChildren } from "bits-ui";
type Props = WithoutChildren<Select.RootProps> & {
placeholder?: string;
items: { value: string; label: string; disabled?: boolean }[];
contentProps?: WithoutChildren<Select.ContentProps>;
// any other specific component props if needed
};
let {
value = $bindable(),
items,
contentProps,
placeholder,
...restProps
}: Props = $props();
</script>
<!--
TypeScript Discriminated Unions + destructing (required for "bindable") do not
get along, so we shut typescript up by casting `value` to `never`, however,
from the perspective of the consumer of this component, it will be typed appropriately.
-->
<Select.Root {items} bind:value={value as never} {...restProps}>
<Select.Trigger>
<Select.Value {placeholder} />
</Select.Trigger>
<Select.Portal>
<Select.Content {...contentProps}>
<Select.ScrollUpButton>up</Select.ScrollUpButton>
<Select.Viewport>
{#each items as { value, label, disabled } (value)}
<Select.Item {value} {label} {disabled}>
{#snippet children({ selected })}
{selected ? "✅" : ""}
{label}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton>down</Select.ScrollDownButton>
</Select.Content>
</Select.Portal>
</Select.Root>
그러면 애플리케이션 곳곳에서 MySelect 컴포넌트를 이렇게 사용할 수 있어요:
<script lang="ts">
import MySelect from "$lib/components/MySelect.svelte";
const items = [
{ value: "apple", label: "Apple" },
{ value: "banana", label: "Banana" },
{ value: "cherry", label: "Cherry" },
];
let fruit = $state("apple");
</script>
<MySelect {items} bind:value={fruit} />
값 상태 다루기 (Managing Value State)
이번 절에서는 컴포넌트의 value 상태를 어떻게 관리하는지 다뤄요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동적인 상태 동기화가 필요하다면 bind:value를 사용하세요:
<script lang="ts">
import { Select } from "bits-ui";
let myValue = $state("");
</script>
<button onclick={() => (myValue = "A")}> Select A </button>
<Select.Root type="single" bind:value={myValue}>
<!-- ... -->
</Select.Root>
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 완전히 제어하고 싶다면 Function Binding을 사용하세요.
<script lang="ts">
import { Select } from "bits-ui";
let myValue = $state("");
function getValue() {
return myValue;
}
function setValue(newValue: string) {
myValue = newValue;
}
</script>
<Select.Root type="single" bind:value={getValue, setValue}>
<!-- ... -->
</Select.Root>
열림 상태 다루기 (Managing Open State)
이번 절에서는 컴포넌트의 open 상태를 어떻게 관리하는지 다뤄요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동적인 상태 동기화가 필요하다면 bind:open을 사용하세요:
<script lang="ts">
import { Select } from "bits-ui";
let myOpen = $state(false);
</script>
<button onclick={() => (myOpen = true)}> Open </button>
<Select.Root bind:open={myOpen}>
<!-- ... -->
</Select.Root>
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 완전히 제어하고 싶다면 Function Binding을 사용하세요.
<script lang="ts">
import { Select } from "bits-ui";
let myOpen = $state(false);
function getOpen() {
return myOpen;
}
function setOpen(newOpen: boolean) {
myOpen = newOpen;
}
</script>
<Select.Root bind:open={getOpen, setOpen}>
<!-- ... -->
</Select.Root>
다중 선택 (Multiple Selection)
type prop을 'multiple'로 설정하면 한 번에 여러 항목을 선택할 수 있어요.
<script lang="ts">
import { Select } from "bits-ui";
let value = $state<string[]>([]);
</script>
<Select.Root type="multiple" bind:value>
<!-- ... -->
</Select.Root>
코드 펼치기 (Expand Code)
<script lang="ts">
import { Select } from "bits-ui";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import Check from "phosphor-svelte/lib/Check";
import Palette from "phosphor-svelte/lib/Palette";
const themes = [
{ value: "light-monochrome", label: "Light Monochrome" },
{ value: "dark-green", label: "Dark Green" },
{ value: "svelte-orange", label: "Svelte Orange" },
{ value: "punk-pink", label: "Punk Pink" },
{ value: "ocean-blue", label: "Ocean Blue" },
{ value: "sunset-red", label: "Sunset Red" },
{ value: "forest-green", label: "Forest Green" },
{ value: "lavender-purple", label: "Lavender Purple" },
{ value: "mustard-yellow", label: "Mustard Yellow" },
{ value: "slate-gray", label: "Slate Gray" },
{ value: "neon-green", label: "Neon Green" },
{ value: "coral-reef", label: "Coral Reef" },
{ value: "midnight-blue", label: "Midnight Blue" },
{ value: "crimson-red", label: "Crimson Red" },
{ value: "mint-green", label: "Mint Green" },
{ value: "pastel-pink", label: "Pastel Pink" },
{ value: "golden-yellow", label: "Golden Yellow" },
{ value: "deep-purple", label: "Deep Purple" },
{ value: "turquoise-blue", label: "Turquoise Blue" },
{ value: "burnt-orange", label: "Burnt Orange" }
];
</script>
<Select.Root type="multiple">
<Select.Trigger
class="h-input rounded-9px border-border-input bg-background data-placeholder:text-foreground-alt/50 inline-flex w-[296px] touch-none select-none items-center border px-[11px] text-sm transition-colors"
aria-label="Select a theme"
>
<Palette class="text-muted-foreground mr-[9px] size-6" />
<Select.Value
class="w-[calc(296px-11px-11px-9px)] truncate text-start"
placeholder="Select your favorite themes"
/>
<CaretUpDown class="text-muted-foreground ml-auto size-6" />
</Select.Trigger>
<Select.Portal>
<Select.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-select-content-available-height)] w-[var(--bits-select-anchor-width)] min-w-[var(--bits-select-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}
>
<Select.ScrollUpButton class="flex w-full items-center justify-center">
<CaretDoubleUp class="size-3" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each themes as theme, i (i + theme.value)}
<Select.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={theme.value}
label={theme.label}
>
{#snippet children({ selected })}
{theme.label}
{#if selected}
<div class="ml-auto">
<Check />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton class="flex w-full items-center justify-center">
<CaretDoubleDown class="size-3" />
</Select.ScrollDownButton>
</Select.Content>
</Select.Portal>
</Select.Root>
Floating UI 사용 안 함 (Opt-out of Floating UI)
Select.Content 컴포넌트를 사용하면 다른 popover 계열 컴포넌트처럼 Bits UI가 Floating UI를 사용해 트리거 기준으로 콘텐츠를 배치해요.
대신 Select.ContentStatic 컴포넌트를 사용하면 이 동작을 해제할 수 있어요.
<Select.Root>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Portal>
<Select.ContentStatic>
<Select.ScrollUpButton />
<Select.Viewport>
<Select.Item />
<Select.Group>
<Select.GroupHeading />
<Select.Item />
</Select.Group>
</Select.Viewport>
<Select.ScrollDownButton />
</Select.ContentStatic>
</Select.Portal>
</Select.Root>
이 컴포넌트를 사용하면 콘텐츠의 위치를 직접 처리해야 해요. Select.ContentStatic과 함께 Select.Portal을 쓰면 예상치 못한 위치 지정 동작이 발생할 수 있으니 참고하세요. 포털을 쓰지 않거나 다른 방식으로 우회해도 좋아요.
커스텀 앵커 (Custom Anchor)
기본적으로 Select.Content는 Select.Trigger 컴포넌트에 앵커되어, 콘텐츠가 놓일 위치가 결정돼요.
대신 다른 요소에 콘텐츠를 앵커하고 싶다면, Select.Content 컴포넌트의 customAnchor prop에 셀렉터 문자열이나 HTMLElement를 전달하면 돼요.
<script lang="ts">
import { Select } from "bits-ui";
let customAnchor = $state<HTMLElement>(null!);
</script>
<div bind:this={customAnchor}></div>
<Select.Root>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Content {customAnchor}>
<!-- ... -->
</Select.Content>
</Select.Root>
Viewport란? (What is the Viewport?)
Select.Viewport 컴포넌트는 콘텐츠의 크기를 파악해서 위/아래 스크롤 버튼을 렌더링할지 결정하는 데 사용돼요.
select 콘텐츠의 최소/최대 높이를 설정하고 싶다면 Select.Viewport 컴포넌트에 적용하세요.
위/아래 스크롤 버튼 (Scroll Up/Down Buttons)
Select.ScrollUpButton과 Select.ScrollDownButton 컴포넌트는 select 콘텐츠가 뷰포트보다 클 때 위/아래 스크롤 버튼을 렌더링하는 데 사용돼요.
스크롤 버튼을 사용할 때는 반드시 Select.Viewport 컴포넌트를 함께 사용해야 해요.
커스텀 스크롤 지연 (Custom Scroll Delay)
처음 및 이후의 스크롤 지연은 버튼의 delay prop으로 조절할 수 있어요.
예를 들어 Svelte의 cubicOut 이징 함수를 사용하면 시간이 지날수록 빨라지는 부드러운 스크롤 효과를 만들 수 있어요.
코드 펼치기 (Expand Code)
<script lang="ts">
import { Select } from "bits-ui";
import Check from "phosphor-svelte/lib/Check";
import Palette from "phosphor-svelte/lib/Palette";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
import { cubicOut } from "svelte/easing";
const themes = [
{ value: "light-monochrome", label: "Light Monochrome" },
{ value: "dark-green", label: "Dark Green" },
{ value: "svelte-orange", label: "Svelte Orange" },
{ value: "punk-pink", label: "Punk Pink" },
{ value: "ocean-blue", label: "Ocean Blue", disabled: true },
{ value: "sunset-orange", label: "Sunset Orange" },
{ value: "sunset-red", label: "Sunset Red" },
{ value: "forest-green", label: "Forest Green" },
{ value: "lavender-purple", label: "Lavender Purple", disabled: true },
{ value: "mustard-yellow", label: "Mustard Yellow" },
{ value: "slate-gray", label: "Slate Gray" },
{ value: "neon-green", label: "Neon Green" },
{ value: "coral-reef", label: "Coral Reef" },
{ value: "midnight-blue", label: "Midnight Blue" },
{ value: "crimson-red", label: "Crimson Red" },
{ value: "mint-green", label: "Mint Green" },
{ value: "pastel-pink", label: "Pastel Pink" },
{ value: "golden-yellow", label: "Golden Yellow" },
{ value: "deep-purple", label: "Deep Purple" },
{ value: "turquoise-blue", label: "Turquoise Blue" },
{ value: "burnt-orange", label: "Burnt Orange" }
];
// Duplicate the menu items a couple of times to show off scrolling a big list
const baseThemes = [...themes];
for (let i = 0; i < 10; i++) {
for (let baseTheme of baseThemes) {
themes.push({ ...baseTheme, value: baseTheme.value + i });
}
}
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>
<Select.Root type="single" items={themes}>
<Select.Trigger
class="h-input rounded-9px border-border-input bg-background data-placeholder:text-foreground-alt/50 inline-flex w-[296px] touch-none select-none items-center border px-[11px] text-sm transition-colors"
aria-label="Select a theme"
>
<Palette class="text-muted-foreground mr-[9px] size-6" />
<Select.Value placeholder="Select a theme" />
<CaretUpDown class="text-muted-foreground ml-auto size-6" />
</Select.Trigger>
<Select.Portal>
<Select.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-select-content-available-height)] w-[var(--bits-select-anchor-width)] min-w-[var(--bits-select-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}
>
<Select.ScrollUpButton
class="flex w-full items-center justify-center"
delay={autoScrollDelay}
>
<CaretDoubleUp class="size-3" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each themes as theme, i (i + theme.value)}
<Select.Item
class="rounded-button data-highlighted:bg-muted outline-hidden data-disabled:opacity-50 flex h-10 w-full select-none items-center py-3 pl-5 pr-1.5 text-sm capitalize"
value={theme.value}
label={theme.label}
disabled={theme.disabled}
>
{#snippet children({ selected })}
{theme.label}
{#if selected}
<div class="ml-auto">
<Check />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton
class="flex w-full items-center justify-center"
delay={autoScrollDelay}
>
<CaretDoubleDown class="size-3" />
</Select.ScrollDownButton>
</Select.Content>
</Select.Portal>
</Select.Root>
네이티브 스크롤/오버플로 (Native Scrolling/Overflow)
스크롤 버튼을 사용하지 않고 표준 스크롤바/오버플로 동작을 쓰고 싶다면, Select.Scroll[Up|Down]Button 컴포넌트와 Select.Viewport 컴포넌트를 생략하면 돼요.
그러려면 Select.Content 컴포넌트에 높이를 설정하고 스크롤이 동작하도록 적절한 overflow 스타일을 지정해야 해요.
스크롤 잠금 (Scroll Lock)
기본적으로 사용자가 select를 열어도 콘텐츠 바깥쪽 스크롤은 비활성화되지 않아요. preventScroll prop을 true로 설정하면 이 동작을 바꿀 수 있어요.
<Select.Content preventScroll={true}>
<!-- ... -->
</Select.Content>
하이라이트된 항목 (Highlighted Items)
Select 컴포넌트는 항목 하이라이트에 WAI-ARIA descendant 패턴을 따르는 표준 방식을 사용해요. 즉 키보드로 이동할 때조차 Select.Trigger가 포커스를 계속 유지하고, 사용자가 이동하면서 항목이 하이라이트돼요.
하이라이트된 항목 스타일링 (Styling Highlighted Items)
Select.Item 컴포넌트의 data-highlighted 속성을 사용하면 항목이 하이라이트될 때 다르게 스타일링할 수 있어요.
onHighlight / onUnhighlight
항목이 하이라이트되거나 해제될 때 부수 효과(side effect)를 실행하려면 onHighlight와 onUnhighlight prop을 사용하세요.
<Select.Item onHighlight={() => console.log('I am highlighted!')} onUnhighlight={() => console.log('I am unhighlighted!')} />
<!-- ... -->
</Select.Item>
Svelte 트랜지션 (Svelte Transitions)
더 많은 제어가 필요한 Svelte 트랜지션이나 다른 애니메이션 라이브러리를 쓰려면 forceMount prop과 child 스니펫을 조합해 Select.Content 컴포넌트를 강제로 마운트할 수 있어요.
<script lang="ts">
import { Select } from "bits-ui";
import { fly } from "svelte/transition";
</script>
<Select.Content forceMount>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:fly>
<!-- ... -->
</div>
</div>
{/if}
{/snippet}
</Select.Content>
물론 이 문법이 가장 깔끔한 건 아니에요. 이 방식을 쓸 계획이라면 이 로직을 처리하는 재사용 가능한 content 컴포넌트를 직접 만드는 걸 권장해요. Bits UI 컴포넌트에서 트랜지션을 사용하는 방법에 대한 자세한 내용은 Transitions 문서를 참고하세요.
코드 펼치기 (Expand Code)
<script lang="ts">
import { Select } from "bits-ui";
import Check from "phosphor-svelte/lib/Check";
import Palette from "phosphor-svelte/lib/Palette";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
import { fly } from "svelte/transition";
const themes = [
{ value: "light-monochrome", label: "Light Monochrome" },
{ value: "dark-green", label: "Dark Green" },
{ value: "svelte-orange", label: "Svelte Orange" },
{ value: "punk-pink", label: "Punk Pink" },
{ value: "ocean-blue", label: "Ocean Blue" },
{ value: "sunset-red", label: "Sunset Red" },
{ value: "forest-green", label: "Forest Green" },
{ value: "lavender-purple", label: "Lavender Purple" },
{ value: "mustard-yellow", label: "Mustard Yellow" },
{ value: "slate-gray", label: "Slate Gray" },
{ value: "neon-green", label: "Neon Green" },
{ value: "coral-reef", label: "Coral Reef" },
{ value: "midnight-blue", label: "Midnight Blue" },
{ value: "crimson-red", label: "Crimson Red" },
{ value: "mint-green", label: "Mint Green" },
{ value: "pastel-pink", label: "Pastel Pink" },
{ value: "golden-yellow", label: "Golden Yellow" },
{ value: "deep-purple", label: "Deep Purple" },
{ value: "turquoise-blue", label: "Turquoise Blue" },
{ value: "burnt-orange", label: "Burnt Orange" }
];
</script>
<Select.Root type="single" items={themes}>
<Select.Trigger
class="h-input rounded-9px border-border-input bg-background placeholder:text-foreground-alt/50 inline-flex w-[296px] touch-none select-none items-center border px-[11px] text-sm transition-colors"
aria-label="Select a theme"
>
<Palette class="text-muted-foreground mr-[9px] size-6" />
<Select.Value placeholder="Select a theme" />
<CaretUpDown class="text-muted-foreground ml-auto size-6" />
</Select.Trigger>
<Select.Portal>
<Select.Content
class="focus-override border-muted bg-background shadow-popover outline-hidden z-50 h-96 max-h-[var(--bits-select-content-available-height)] w-[var(--bits-select-anchor-width)] min-w-[var(--bits-select-anchor-width)] select-none 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 }}>
<Select.ScrollUpButton
class="flex w-full items-center justify-center"
>
<CaretDoubleUp class="size-3" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each themes as theme, i (i + theme.value)}
<Select.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 duration-75"
value={theme.value}
label={theme.label}
>
{#snippet children({ selected })}
{theme.label}
{#if selected}
<div class="ml-auto">
<Check />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton
class="flex w-full items-center justify-center"
>
<CaretDoubleDown class="size-3" />
</Select.ScrollDownButton>
</div>
</div>
{/if}
{/snippet}
</Select.Content>
</Select.Portal>
</Select.Root>
Select.Value 커스터마이즈 (Customizing Select.Value)
Select.Value 컴포넌트에서 값의 렌더링을 커스터마이즈하려면 child 또는 children 스니펫을 사용할 수 있어요.
<Select.Value>
{#snippet child({ props, selection, placeholder, disabled })}
<div {...props}>
<!-- ... -->
</div>
<!-- ... -->
{/snippet}
</Select.Value>
<Select.Value>
{#snippet children({ selection, placeholder, disabled })}
<!-- ... -->
{/snippet}
</Select.Value>
이렇게 하면 값을 원하는 대로 표시하고 수정할 수 있어요.
<script lang="ts">
import { Select } from "bits-ui";
import Check from "phosphor-svelte/lib/Check";
import Palette from "phosphor-svelte/lib/Palette";
import CaretUpDown from "phosphor-svelte/lib/CaretUpDown";
import CaretDoubleUp from "phosphor-svelte/lib/CaretDoubleUp";
import CaretDoubleDown from "phosphor-svelte/lib/CaretDoubleDown";
import X from "phosphor-svelte/lib/X";
const themes = [
{ value: "light-monochrome", label: "Light Monochrome" },
{ value: "dark-green", label: "Dark Green" },
{ value: "svelte-orange", label: "Svelte Orange" },
{ value: "punk-pink", label: "Punk Pink" },
{ value: "ocean-blue", label: "Ocean Blue", disabled: true },
{ value: "sunset-orange", label: "Sunset Orange" },
{ value: "sunset-red", label: "Sunset Red" },
{ value: "forest-green", label: "Forest Green" },
{ value: "lavender-purple", label: "Lavender Purple", disabled: true },
{ value: "mustard-yellow", label: "Mustard Yellow" },
{ value: "slate-gray", label: "Slate Gray" },
{ value: "neon-green", label: "Neon Green" },
{ value: "coral-reef", label: "Coral Reef" },
{ value: "midnight-blue", label: "Midnight Blue" },
{ value: "crimson-red", label: "Crimson Red" },
{ value: "mint-green", label: "Mint Green" },
{ value: "pastel-pink", label: "Pastel Pink" },
{ value: "golden-yellow", label: "Golden Yellow" },
{ value: "deep-purple", label: "Deep Purple" },
{ value: "turquoise-blue", label: "Turquoise Blue" },
{ value: "burnt-orange", label: "Burnt Orange" }
];
</script>
<Select.Root type="multiple" items={themes} allowDeselect={true}>
<Select.Trigger
class="h-input rounded-9px border-border-input bg-background data-placeholder:text-foreground-alt/50 inline-flex w-[296px] touch-none select-none items-center border px-[11px] text-sm transition-colors"
aria-label="Select a theme"
>
<Palette class="text-muted-foreground mr-[9px] size-6 shrink-0" />
<Select.Value placeholder="Select your favorite themes">
{#snippet child({ props, selection, placeholder, disabled })}
<div
{...props}
class="flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
>
{#if selection.type === "multiple" && selection.selected.length > 0}
{#each selection.selected as selectedTheme (selectedTheme.value)}
<div
class="rounded-button bg-muted flex shrink-0 items-center gap-0.5 py-0.5 pl-2 pr-1 text-sm"
>
<span class="text-nowrap">{selectedTheme.label}</span>
<div
role="button"
tabindex={0}
aria-disabled={disabled}
aria-label="Remove {selectedTheme.label}"
onpointerdown={(e) => e.stopPropagation()}
onpointerup={(e) => e.stopPropagation()}
onkeydown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.currentTarget.click();
}
}}
onclick={(e) => {
if (disabled) return;
e.stopPropagation();
e.preventDefault();
selection.setValue(
selection.selected
.filter((theme) => theme.value !== selectedTheme.value)
.map((theme) => theme.value)
);
}}
class="text-muted-foreground hover:bg-background/60 hover:text-foreground rounded-sm p-0.5 transition-colors disabled:cursor-not-allowed"
>
<X class="size-3" />
</div>
</div>
{/each}
{:else}
<span class="text-foreground-alt/50 truncate">{placeholder}</span>
{/if}
</div>
{/snippet}
</Select.Value>
<CaretUpDown class="text-muted-foreground ml-2 size-6 shrink-0" />
</Select.Trigger>
<Select.Portal>
<Select.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-select-content-available-height)] w-[var(--bits-select-anchor-width)] min-w-[var(--bits-select-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}
>
<Select.ScrollUpButton class="flex w-full items-center justify-center">
<CaretDoubleUp class="size-3" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each themes as theme, i (i + theme.value)}
<Select.Item
class="rounded-button data-highlighted:bg-muted outline-hidden data-disabled:opacity-50 flex h-10 w-full select-none items-center py-3 pl-5 pr-1.5 text-sm capitalize"
value={theme.value}
label={theme.label}
disabled={theme.disabled}
>
{#snippet children({ selected })}
{theme.label}
{#if selected}
<div class="ml-auto">
<Check aria-label="check" />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton class="flex w-full items-center justify-center">
<CaretDoubleDown class="size-3" />
</Select.ScrollDownButton>
</Select.Content>
</Select.Portal>
</Select.Root>
API 참조 (API Reference)
Select.Root
select의 상태를 관리하고 범위를 지정하는 루트 select 컴포넌트예요.
| Property | Type | Description | Details |
|---|---|---|---|
type required |
enum - 'single' | 'multiple' |
The type of the component, used to determine the type of the value, when 'multiple' the value will be an array.Default: —— undefined |
|
value $bindable |
union - string | string[] |
The value of the select. When the type is 'single', this should be a string. When the type is 'multiple', this should be an array of strings.Default: string |
|
onValueChange |
function - (value: string) => void | (value: string[]) => void |
A callback that is fired when the select 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 component.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 select 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 select.Default: —— undefined |
|
required |
boolean |
Whether or not the select menu is required. When required is true, a name attribute must also be provided so that the hidden input is renderedDefault: false |
|
scrollAlignment |
enum - 'nearest' | 'center' |
The alignment of the highlighted item when scrolling.Default: 'nearest' |
|
loop |
boolean |
Whether or not the select 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: false |
|
items |
object - { value: string; label: string; disabled?: boolean}[] |
Optionally provide an array of value and label pairs that will be used to match and trigger selection when the trigger is focused and a key is pressed while the content is closed. Additionally, this will be used for form autofill when the type is single.Default: —— undefined |
|
autocomplete |
string |
The autocomplete attribute to forward to the hidden input element.Default: —— undefined |
|
children |
Snippet |
The children content to render.Default: —— undefined |
Select.Trigger
select의 열림 상태를 토글하는 버튼이에요.
| 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 select's open state. | |
data-placeholder |
'' |
Present when the select does not have a value. | |
data-disabled |
'' |
Present when the select is disabled. | |
data-select-trigger |
'' |
Present on the trigger element. |
Select.Value
현재 선택된 항목의 텍스트 라벨이에요. 기본적으로 ``를 렌더링하며, child 스니펫을 사용하면 완전히 제어할 수 있어요.
| Property | Type | Description | Details |
|---|---|---|---|
placeholder |
string |
Text shown when no value is selected.Default: —— undefined |
|
children |
Snippet - type ChildrenSnippetProps = { selection: | { type: "single" selected?: { value: string; label: string } setValue: (value: string) => void } | { type: "multiple" selected: { value: string; label: string }[] setValue: (value: string[]) => void } placeholder: string | null disabled: boolean } |
The children content to render.Default: —— undefined |
|
child |
Snippet - type ChildSnippetProps = { props: Record<string, unknown> selection: | { type: "single" selected?: { value: string; label: string } setValue: (value: string) => void } | { type: "multiple" selected: { value: string; label: string }[] setValue: (value: string[]) => void } placeholder: string | null disabled: boolean } |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
|
ref $bindable |
HTMLSpanElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-placeholder |
'' |
Present when the select does not have a value. | |
data-select-value |
'' |
Present on the value element. |
Select.Content
select의 항목들을 담고 있는 요소예요.
| 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 select 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 select'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-select-content |
'' |
Present on the content element. |
| CSS Variable | Description | Details |
|---|---|---|
--bits-select-content-transform-origin |
The transform origin of the content element. | |
--bits-select-content-available-width |
The available width of the content element. | |
--bits-select-content-available-height |
The available height of the content element. | |
--bits-select-anchor-width |
The width of the anchor element. | |
--bits-select-anchor-height |
The height of the anchor element. |
Select.ContentStatic
select의 항목들을 담고 있는 요소예요. (Static/No Floating 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 select 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 select'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-select-content |
'' |
Present on the content element. |
Select.Portal
사용하면 select 콘텐츠가 열릴 때 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 |
Select.Item
select.Content 컴포넌트의 자식이어야 하는 select 항목이에요.
| 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 using typeahead behavior.Default: —— undefined |
|
disabled |
boolean |
Whether or not the select 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 select item. | |
data-label |
string |
The label of the select 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-select-item |
'' |
Present on the item element. |
Select.Viewport
위/아래 스크롤 버튼을 렌더링하기 위해 select의 스크롤 위치를 추적하는 선택적 요소예요.
| 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-select-viewport |
'' |
Present on the viewport element. |
Select.ScrollUpButton
select 안의 스크롤 경험을 개선하는 선택적 위쪽 스크롤 버튼 요소예요. select.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-select-scroll-up-button |
'' |
Present on the scroll up button element. |
Select.ScrollDownButton
select 안의 스크롤 경험을 개선하는 선택적 아래쪽 스크롤 버튼 요소예요. select.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-select-scroll-down-button |
'' |
Present on the scroll down button element. |
Select.Group
관련된 select 항목들의 그룹이에요.
| 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-select-group |
'' |
Present on the group element. |
Select.GroupHeading
부모 select 그룹의 제목이에요. 관련된 select 항목들의 그룹을 설명하는 데 사용돼요.
| 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-select-group-heading |
'' |
Present on the group heading element. |
Select.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)
Select는 옵션을 고르는 핵심 컴포넌트예요. 더 자유로운 입력과 선택이 함께 필요하면 Combobox를, 관련 항목을 여러 개 고르도록 구성할 때는 Checkbox를 함께 알아 두면 좋아요. 콘텐츠 배치 방식은 Popover와 비슷하니 참고하면 도움이 돼요.