Select
Select (셀렉트)
사용자가 선택할 수 있는 옵션 목록을 표시하는 컴포넌트예요. 단일/다중 선택, 그룹화, 가상화, 폼 통합 등 다양한 기능을 지원하는 드롭다운 컨트롤이에요.
출처: 문서
본문
구조 (Anatomy)
셀렉트의 기본 구조는 다음과 같아요. Root 안에 Label, Control(트리거와 인디케이터), 그리고 Positioner로 감싼 Content와 각 Item들을 배치해요.
<Select.Root>
<Select.Label />
<Select.Control>
<Select.Trigger>
<Select.ValueText />
</Select.Trigger>
<Select.ClearTrigger />
<Select.Indicator />
</Select.Control>
<Select.Positioner>
<Select.Content>
<Select.ItemGroup>
<Select.ItemGroupLabel />
<Select.Item>
<Select.ItemText />
<Select.ItemIndicator />
</Select.Item>
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
<Select.HiddenSelect />
</Select.Root>
예제 (Examples)
기본 (Basic)
createListCollection으로 옵션 컬렉션을 만들고, 각 Select.Item에 item을 전달해요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
const frameworks = createListCollection({
items: [
{ label: 'React', value: 'react' },
{ label: 'Solid', value: 'solid' },
{ label: 'Vue', value: 'vue' },
{ label: 'Svelte', value: 'svelte' },
],
})
export const Basic = () => {
return (
<Select.Root className={styles.Root} collection={frameworks}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select" />
</Select.Trigger>
<div className={styles.Indicators}>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</div>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{frameworks.items.map((item) => (
<Select.Item className={styles.Item} key={item.value} item={item}>
<Select.ItemText className={styles.ItemText}>{item.label}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
제어된 방식 (Controlled)
value와 onValueChange prop을 사용해서 선택된 항목을 제어해요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/select.module.css'
interface Item {
label: string
value: string
disabled?: boolean | undefined
}
export const Controlled = () => {
const [value, setValue] = useState<string[]>([])
const collection = createListCollection<Item>({
items: [
{ label: 'React', value: 'react' },
{ label: 'Solid', value: 'solid' },
{ label: 'Vue', value: 'vue' },
{ label: 'Svelte', value: 'svelte', disabled: true },
],
})
const handleValueChange = (details: Select.ValueChangeDetails<Item>) => {
setValue(details.value)
}
return (
<Select.Root className={styles.Root} collection={collection} value={value} onValueChange={handleValueChange}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
</Select.Trigger>
<div className={styles.Indicators}>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</div>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item.value} item={item}>
<Select.ItemText className={styles.ItemText}>{item.label}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
루트 프로바이더 (Root Provider)
셀렉트를 제어하는 또 다른 방법은 RootProvider 컴포넌트와 useSelect 훅을 사용하는 거예요. 이렇게 하면 컴포넌트 밖에서 상태와 메서드에 접근할 수 있어요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection, useSelect } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
const frameworks = createListCollection({
items: [
{ label: 'React', value: 'react' },
{ label: 'Solid', value: 'solid' },
{ label: 'Vue', value: 'vue' },
{ label: 'Svelte', value: 'svelte' },
],
})
export const RootProvider = () => {
const select = useSelect({ collection: frameworks })
return (
<>
<output>selected: {JSON.stringify(select.value)}</output>
<Select.RootProvider className={styles.Root} value={select}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
</Select.Trigger>
<div className={styles.Indicators}>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</div>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{frameworks.items.map((item) => (
<Select.Item className={styles.Item} key={item.value} item={item}>
<Select.ItemText className={styles.ItemText}>{item.label}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.RootProvider>
</>
)
}
다중 선택 (Multiple)
multiple 항목 선택을 활성화하려면:
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
const frameworks = createListCollection({
items: [
{ label: 'React', value: 'react' },
{ label: 'Solid', value: 'solid' },
{ label: 'Vue', value: 'vue' },
{ label: 'Svelte', value: 'svelte', disabled: true },
],
})
export const Multiple = () => {
return (
<Select.Root className={styles.Root} collection={frameworks} multiple>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select" />
</Select.Trigger>
<div className={styles.Indicators}>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</div>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{frameworks.items.map((item) => (
<Select.Item className={styles.Item} key={item.value} item={item}>
<Select.ItemText className={styles.ItemText}>{item.label}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
그룹화 (Grouping)
관련 옵션을 그룹으로 묶으면 옵션을 카테고리로 정리하는 데 유용해요.
groupByprop을 사용해서 항목의 그룹화를 구성해요.collection.group()메서드로 그룹화된 항목을 가져와요.Select.ItemGroup과Select.ItemGroupLabel컴포넌트로 그룹화된 항목을 렌더링해요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
const frameworks = createListCollection({
items: [
{ label: 'React', value: 'react', type: 'JS' },
{ label: 'Solid', value: 'solid', type: 'JS' },
{ label: 'Vue', value: 'vue', type: 'JS' },
{ label: 'Panda', value: 'panda', type: 'CSS' },
{ label: 'Tailwind', value: 'tailwind', type: 'CSS' },
],
groupBy: (item) => item.type,
})
export const Grouping = () => {
return (
<Select.Root className={styles.Root} collection={frameworks}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
</Select.Trigger>
<div className={styles.Indicators}>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</div>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
{frameworks.group().map(([type, group]) => (
<Select.ItemGroup className={styles.ItemGroup} key={type}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>{type}</Select.ItemGroupLabel>
{group.map((item) => (
<Select.Item className={styles.Item} key={item.value} item={item}>
<Select.ItemText className={styles.ItemText}>{item.label}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
))}
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
Field 함께 사용하기 (Field)
Field를 사용해서 폼 상태, ARIA 라벨, 도우미 텍스트, 오류 텍스트를 관리해요.
import { Field } from '@ark-ui/react/field'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon } from 'lucide-react'
import field from 'styles/field.module.css'
import styles from 'styles/select.module.css'
export const WithField = () => {
const collection = createListCollection({ items: ['React', 'Solid', 'Vue', 'Svelte'] })
return (
<Field.Root className={field.Root}>
<Select.Root collection={collection} className={styles.Root}>
<Select.Label className={styles.Label}>Label</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
</Select.Control>
<Select.Positioner>
<Select.Content className={styles.Content}>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.Content>
</Select.Positioner>
<Select.HiddenSelect />
</Select.Root>
<Field.HelperText className={field.HelperText}>Additional Info</Field.HelperText>
<Field.ErrorText className={field.ErrorText}>Error Info</Field.ErrorText>
</Field.Root>
)
}
폼 사용 (Form Usage)
Select 컴포넌트를 폼 라이브러리와 통합하는 예제예요.
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import { Controller, type SubmitHandler, useForm } from 'react-hook-form'
import button from 'styles/button.module.css'
import styles from 'styles/select.module.css'
interface Inputs {
framework: string
}
export const FormLibrary = () => {
const { control, handleSubmit } = useForm<Inputs>({
defaultValues: { framework: 'React' },
})
const collection = createListCollection({
items: ['React', 'Solid', 'Vue', 'Svelte'],
})
const onSubmit: SubmitHandler<Inputs> = (data) => {
window.alert(JSON.stringify(data))
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="framework"
control={control}
render={({ field }) => (
<Select.Root
className={styles.Root}
collection={collection}
value={field.value ? [field.value] : []}
onValueChange={(e) => field.onChange(e.value[0])}
name={field.name}
onInteractOutside={() => field.onBlur()}
>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.HiddenSelect />
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
</Select.Trigger>
<div className={styles.Indicators}>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</div>
</Select.Control>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Select.Root>
)}
/>
<button className={button.Root} style={{ marginTop: '1rem' }} type="submit">
Submit
</button>
</form>
)
}
비동기 로딩 (Async Loading)
셀렉트가 열릴 때 항목을 비동기적으로 로드하는 예제예요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/select.module.css'
function loadData() {
return new Promise<string[]>((resolve) => {
setTimeout(() => resolve(['React', 'Solid', 'Vue', 'Svelte', 'Angular', 'Ember']), 500)
})
}
export const Async = () => {
const [items, setItems] = useState<string[] | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)
const collection = createListCollection<string>({
items: items || [],
})
const handleOpenChange = (details: Select.OpenChangeDetails) => {
if (details.open && items == null) {
setLoading(true)
setError(null)
loadData()
.then((data) => setItems(data))
.catch((err) => setError(err))
.finally(() => setLoading(false))
}
}
return (
<Select.Root className={styles.Root} collection={collection} onOpenChange={handleOpenChange}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
{loading ? (
<div className={styles.Item}>Loading...</div>
) : error ? (
<div className={styles.Item}>Error: {error.message}</div>
) : (
collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))
)}
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
지연 마운트 (Lazy Mount)
lazyMount와 unmountOnExit를 사용해서 콘텐츠가 마운트되는 시점을 제어해 성능을 개선해요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
export const LazyMount = () => {
const collection = createListCollection({
items: ['React', 'Solid', 'Vue', 'Svelte', 'Angular', 'Alpine'],
})
return (
<Select.Root className={styles.Root} collection={collection} lazyMount unmountOnExit>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
<Select.ClearTrigger className={styles.ClearTrigger}>Clear</Select.ClearTrigger>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
강조 시 선택 (Select on Highlight)
항목이 강조(호버 또는 키보드 탐색)될 때 자동으로 선택하는 예제예요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection, useSelect } from '@ark-ui/react/select'
import { ChevronsUpDownIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
export const SelectOnHighlight = () => {
const collection = createListCollection({
items: ['React', 'Solid', 'Vue', 'Svelte'],
})
const select = useSelect({
collection,
onHighlightChange({ highlightedValue }) {
if (highlightedValue) {
select.selectValue(highlightedValue)
}
},
})
return (
<Select.RootProvider className={styles.Root} value={select}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
<Select.ClearTrigger className={styles.ClearTrigger}>Clear</Select.ClearTrigger>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.RootProvider>
)
}
최대 선택 개수 (Max Selection)
다중 선택 셀렉트에서 선택할 수 있는 항목 수를 제한하는 예제예요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/select.module.css'
const items = ['React', 'Solid', 'Vue', 'Svelte']
const MAX_SELECTION = 2
const hasReachedMax = (value: string[]) => value.length >= MAX_SELECTION
export const MaxSelected = () => {
const [value, setValue] = useState<string[]>([])
const collection = createListCollection({
items: items.map((item) => ({
label: item,
value: item,
disabled: hasReachedMax(value) && !value.includes(item),
})),
})
const handleValueChange = (details: Select.ValueChangeDetails) => {
if (hasReachedMax(value) && details.value.length > value.length) return
setValue(details.value)
}
return (
<Select.Root
className={styles.Root}
collection={collection}
multiple
value={value}
onValueChange={handleValueChange}
>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
<Select.ClearTrigger className={styles.ClearTrigger}>
<XIcon />
</Select.ClearTrigger>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Frameworks</Select.ItemGroupLabel>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item.value} item={item}>
<Select.ItemText className={styles.ItemText}>{item.label}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
전체 선택 (Select All)
셀렉트 컨텍스트의 selectAll()을 사용해서 모든 항목을 한 번에 선택해요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
import button from 'styles/button.module.css'
const SelectAllButton = () => {
return (
<Select.Context>
{(api) => (
<button
className={button.Root}
style={{ width: '100%', marginBottom: '0.25rem' }}
type="button"
onClick={() => {
api.selectAll()
api.setOpen(false)
}}
>
Select All
</button>
)}
</Select.Context>
)
}
export const SelectAll = () => {
const collection = createListCollection({ items: ['React', 'Solid', 'Vue', 'Svelte'] })
return (
<Select.Root className={styles.Root} collection={collection}>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
<Select.ClearTrigger className={styles.ClearTrigger}>Clear</Select.ClearTrigger>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content}>
<SelectAllButton />
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
넘침 (Overflow)
항목이 많은 셀렉트에서는 positioning.fitViewport를 사용해서 드롭다운이 뷰포트 안에 맞도록 해요. 콘텐츠에 max-height를 결합하면 스크롤이 가능해져요.
import { Portal } from '@ark-ui/react/portal'
import { Select, createListCollection } from '@ark-ui/react/select'
import { ChevronsUpDownIcon } from 'lucide-react'
import styles from 'styles/select.module.css'
export const Overflow = () => {
const collection = createListCollection({
items: [
'Name 1',
'Name 2',
'Name 3',
'Name 4',
'Name 5',
'Name 6',
'Name 7',
'Name 8',
'Name 9',
'Name 10',
'Name 11',
'Name 12',
'Name 13',
'Name 14',
],
})
return (
<Select.Root
className={styles.Root}
collection={collection}
positioning={{
fitViewport: true,
placement: 'bottom-start',
sameWidth: true,
}}
>
<Select.Label className={styles.Label}>Framework</Select.Label>
<Select.Control className={styles.Control}>
<Select.Trigger className={styles.Trigger}>
<Select.ValueText className={styles.ValueText} placeholder="Select a Framework" />
<Select.Indicator className={styles.Indicator}>
<ChevronsUpDownIcon />
</Select.Indicator>
</Select.Trigger>
<Select.ClearTrigger className={styles.ClearTrigger}>Clear</Select.ClearTrigger>
</Select.Control>
<Portal>
<Select.Positioner>
<Select.Content className={styles.Content} style={{ maxHeight: '200px' }}>
<Select.ItemGroup className={styles.ItemGroup}>
<Select.ItemGroupLabel className={styles.ItemGroupLabel}>Names</Select.ItemGroupLabel>
{collection.items.map((item) => (
<Select.Item className={styles.Item} key={item} item={item}>
<Select.ItemText className={styles.ItemText}>{item}</Select.ItemText>
<Select.ItemIndicator className={styles.ItemIndicator}>✓</Select.ItemIndicator>
</Select.Item>
))}
</Select.ItemGroup>
</Select.Content>
</Select.Positioner>
</Portal>
<Select.HiddenSelect />
</Select.Root>
)
}
가이드 (Guides)
타입 안전성 (Type Safety)
Select.RootComponent 타입을 사용하면 컬렉션 항목에 대한 완전한 타입 안전성을 유지하는 타입 지정 래퍼 컴포넌트를 만들 수 있어요.
const Select: ArkSelect.RootComponent = (props) => {
return <ArkSelect.Root {...props}>{/* ... */}</ArkSelect.Root>
}
onValueChange 및 기타 콜백에 대한 완전한 타입 추론과 함께 래퍼를 사용해요:
const App = () => {
const collection = createListCollection({
initialItems: [
{ label: 'React', value: 'react' },
{ label: 'Vue', value: 'vue' },
],
})
return (
<Select
collection={collection}
onValueChange={(e) => {
// e.items is typed as Array<{ label: string, value: string }>
console.log(e.items)
}}
>
{/* ... */}
</Select>
)
}
숨겨진 셀렉트 (Hidden Select)
Select.HiddenSelect 컴포넌트는 시각적으로 숨겨져 있지만 DOM에 남아 있는 네이티브 HTML <select> 요소를 렌더링해요. 이 컴포넌트는 다음에 필수적이에요:
- 폼 제출: 실제
<select>요소가 DOM에 존재하므로 네이티브 폼 제출과 직렬화가 원활하게 동작해요 - 브라우저 자동 채움: 브라우저가 이전에 제출한 폼 데이터를 기반으로 셀렉트를 올바르게 자동 채울 수 있어요
- 점진적 향상: JavaScript가 로드되지 않아도 폼이 계속 동작해요
<Select.Root>
<Select.HiddenSelect />
{/* Other Select components */}
</Select.Root>
숨겨진 셀렉트는 Select 컴포넌트의 값과 자동으로 동기화되어 폼 데이터가 항상 최신 상태를 유지돼요.
가상화 (Virtualization)
항목이 많은 가상화된 목록에서는 Select.HiddenSelect를 사용하지 않는 게 좋아요. 컬렉션의 모든 항목에 대해 <option>을 렌더링하기 때문이에요. 대신 가벼운 숨겨진 input을 만들어요:
import { Select, useSelectContext } from '@ark-ui/react/select'
const SelectHiddenInput = ({ name }: { name: string }) => {
const select = useSelectContext()
return (
<>
{select.value.map((value) => (
<input key={value} type="hidden" name={name} value={value} />
))}
</>
)
}
빈 상태 (Empty State)
컬렉션에 항목이 없을 때 표시되는 빈 상태 컴포넌트를 만들 수 있어요. useSelectContext 훅으로 컬렉션 크기를 확인해요:
const SelectEmpty = (props: React.ComponentProps<'div'>) => {
const select = useSelectContext()
if (select.collection.size === 0) {
return <div {...props} role="presentation" />
}
return null
}
그런 다음 Select 콘텐츠 안에서 사용해요:
<Select.Content>
<SelectEmpty>No items to display</SelectEmpty>
{/* Your items */}
</Select.Content>
사용 가능한 크기 (Available Size)
Select.Positioner에는 Select.Content 스타일링에 사용할 수 있는 다음 css 변수가 노출돼요.
/* width of the select trigger */
--reference-width: <pixel-value>;
/* width of the available viewport */
--available-width: <pixel-value>;
/* height of the available viewport */
--available-height: <pixel-value>;
예를 들어 최대 높이가 사용 가능한 높이를 넘지 않도록 하려면 다음을 사용할 수 있어요:
[data-scope='select'][data-part='content'] {
max-height: calc(var(--available-height) - 100px);
}
API 레퍼런스 (API Reference)
속성 (Props)
Root
Props
collection
Type: ListCollection<T>
Required: true
Default Value: undefined
Description: The collection of items
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
autoComplete
Type: string
Required: false
Default Value: undefined
Description: The autocomplete attribute for the hidden select. Enables browser autofill (e.g. "address-level1" for state).
closeOnSelect
Type: boolean
Required: false
Default Value: true
Description: Whether the select should close after an item is selected
composite
Type: boolean
Required: false
Default Value: true
Description: Whether the select is a composed with other composite widgets like tabs or combobox
defaultHighlightedValue
Type: string
Required: false
Default Value: undefined
Description: The initial value of the highlighted item when opened.
Use when you don't need to control the highlighted value of the select.
defaultOpen
Type: boolean
Required: false
Default Value: undefined
Description: Whether the select's open state is controlled by the user
defaultValue
Type: string[]
Required: false
Default Value: undefined
Description: The initial default value of the select when rendered.
Use when you don't need to control the value of the select.
deselectable
Type: boolean
Required: false
Default Value: undefined
Description: Whether the value can be cleared by clicking the selected item.
Note: this is only applicable for single selection
disabled
Type: boolean
Required: false
Default Value: undefined
Description: Whether the select is disabled
form
Type: string
Required: false
Default Value: undefined
Description: The associate form of the underlying select.
hideMode
Type: HideMode
Required: false
Default Value: 'display-none'
Description: How to hide content when mounted but not present.
'display-none': HTMLhiddenattribute. Effects stay alive.'activity': React 19<Activity mode="hidden">. Effects pause. Requires React 19+.
highlightedValue
Type: string
Required: false
Default Value: undefined
Description: The controlled key of the highlighted item
id
Type: string
Required: false
Default Value: undefined
Description: The unique identifier of the machine.
ids
Type: Partial<{ root: string content: string control: string trigger: string clearTrigger: string label: string hiddenSelect: string positioner: string item: (id: string | number) => string itemGroup: (id: string | number) => string itemGroupLabel: (id: string | number) => string }>
Required: false
Default Value: undefined
Description: The ids of the elements in the select. Useful for composition.
immediate
Type: boolean
Required: false
Default Value: undefined
Description: Whether to synchronize the present change immediately or defer it to the next frame
invalid
Type: boolean
Required: false
Default Value: undefined
Description: Whether the select is invalid
lazyMount
Type: boolean
Required: false
Default Value: false
Description: Whether to enable lazy mounting
loopFocus
Type: boolean
Required: false
Default Value: false
Description: Whether to loop the keyboard navigation through the options
multiple
Type: boolean
Required: false
Default Value: undefined
Description: Whether to allow multiple selection
name
Type: string
Required: false
Default Value: undefined
Description: The name attribute of the underlying select.
onExitComplete
Type: VoidFunction
Required: false
Default Value: undefined
Description: Function called when the animation ends in the closed state
onFocusOutside
Type: (event: FocusOutsideEvent) => void
Required: false
Default Value: undefined
Description: Function called when the focus is moved outside the component
onHighlightChange
Type: (details: HighlightChangeDetails<T>) => void
Required: false
Default Value: undefined
Description: The callback fired when the highlighted item changes.
onInteractOutside
Type: (event: InteractOutsideEvent) => void
Required: false
Default Value: undefined
Description: Function called when an interaction happens outside the component
onOpenChange
Type: (details: OpenChangeDetails) => void
Required: false
Default Value: undefined
Description: Function called when the popup is opened
onPointerDownOutside
Type: (event: PointerDownOutsideEvent) => void
Required: false
Default Value: undefined
Description: Function called when the pointer is pressed down outside the component
onSelect
Type: (details: SelectionDetails) => void
Required: false
Default Value: undefined
Description: Function called when an item is selected
onValueChange
Type: (details: ValueChangeDetails<T>) => void
Required: false
Default Value: undefined
Description: The callback fired when the selected item changes.
open
Type: boolean
Required: false
Default Value: undefined
Description: Whether the select menu is open
positioning
Type: PositioningOptions
Required: false
Default Value: undefined
Description: The positioning options of the menu.
present
Type: boolean
Required: false
Default Value: undefined
Description: Whether the node is present (controlled by the user)
readOnly
Type: boolean
Required: false
Default Value: undefined
Description: Whether the select is read-only
required
Type: boolean
Required: false
Default Value: undefined
Description: Whether the select is required
scrollToIndexFn
Type: (details: ScrollToIndexDetails) => void
Required: false
Default Value: undefined
Description: Function to scroll to a specific index
skipAnimationOnMount
Type: boolean
Required: false
Default Value: false
Description: Whether to allow the initial presence animation.
translations
Type: IntlTranslations
Required: false
Default Value: undefined
Description: Specifies the localized strings that identifies the accessibility elements and their states
unmountOnExit
Type: boolean
Required: false
Default Value: false
Description: Whether to unmount on exit.
value
Type: string[]
Required: false
Default Value: undefined
Description: The controlled keys of the selected items
데이터 속성 (Data Attributes)
data-scope: select
data-part: root
data-invalid: Present when invalid
data-readonly: Present when read-only
ClearTrigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: clear-trigger
data-invalid: Present when invalid
Content
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: content
data-state: "open" | "closed"
data-nested: listbox
data-has-nested: listbox
data-placement: The placement of the content
data-side: The side of the trigger that the content is positioned on
data-activedescendant: The id the active descendant of the content
Control
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: control
data-state: "open" | "closed"
data-focus: Present when focused
data-disabled: Present when disabled
data-invalid: Present when invalid
HiddenSelect
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
Indicator
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: indicator
data-state: "open" | "closed"
data-disabled: Present when disabled
data-invalid: Present when invalid
data-readonly: Present when read-only
ItemGroupLabel
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
ItemGroup
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: item-group
data-disabled: Present when disabled
ItemIndicator
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: item-indicator
data-state: "checked" | "unchecked"
Item
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
item
Type: any
Required: false
Default Value: undefined
Description: The item to render
persistFocus
Type: boolean
Required: false
Default Value: undefined
Description: Whether hovering outside should clear the highlighted state
데이터 속성 (Data Attributes)
data-scope: select
data-part: item
data-value: The value of the item
data-state: "checked" | "unchecked"
data-highlighted: Present when highlighted
data-disabled: Present when disabled
ItemText
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: item-text
data-state: "checked" | "unchecked"
data-disabled: Present when disabled
data-highlighted: Present when highlighted
Label
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: label
data-disabled: Present when disabled
data-invalid: Present when invalid
data-readonly: Present when read-only
data-required: Present when required
List
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
Positioner
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
RootProvider
Props
value
Type: UseSelectReturn<T>
Required: true
Default Value: undefined
Description: undefined
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
hideMode
Type: HideMode
Required: false
Default Value: 'display-none'
Description: How to hide content when mounted but not present.
'display-none': HTMLhiddenattribute. Effects stay alive.'activity': React 19<Activity mode="hidden">. Effects pause. Requires React 19+.
immediate
Type: boolean
Required: false
Default Value: undefined
Description: Whether to synchronize the present change immediately or defer it to the next frame
lazyMount
Type: boolean
Required: false
Default Value: false
Description: Whether to enable lazy mounting
onExitComplete
Type: VoidFunction
Required: false
Default Value: undefined
Description: Function called when the animation ends in the closed state
present
Type: boolean
Required: false
Default Value: undefined
Description: Whether the node is present (controlled by the user)
skipAnimationOnMount
Type: boolean
Required: false
Default Value: false
Description: Whether to allow the initial presence animation.
unmountOnExit
Type: boolean
Required: false
Default Value: false
Description: Whether to unmount on exit.
Trigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
데이터 속성 (Data Attributes)
data-scope: select
data-part: trigger
data-state: "open" | "closed"
data-disabled: Present when disabled
data-invalid: Present when invalid
data-readonly: Present when read-only
data-placement: The placement of the trigger
data-side: The side of the trigger that the trigger is positioned on
data-placeholder-shown: Present when placeholder is shown
ValueText
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
placeholder
Type: string
Required: false
Default Value: undefined
Description: Text to display when no value is selected.
데이터 속성 (Data Attributes)
data-scope: select
data-part: value-text
data-disabled: Present when disabled
data-invalid: Present when invalid
data-focus: Present when focused
컨텍스트 (Context)
API:
| Property | Type | Description |
|---|---|---|
focused |
boolean |
Whether the select is focused |
open |
boolean |
Whether the select is open |
empty |
boolean |
Whether the select value is empty |
highlightedValue |
`string | null` |
highlightedItem |
`V | null` |
setHighlightValue |
(value: string) => void |
Function to highlight a value |
clearHighlightValue |
VoidFunction |
Function to clear the highlighted value |
selectedItems |
V[] |
The selected items |
hasSelectedItems |
boolean |
Whether there's a selected option |
value |
string[] |
The selected item keys |
valueAsString |
string |
The string representation of the selected items |
selectValue |
(value: string) => void |
Function to select a value |
selectAll |
VoidFunction |
Function to select all values |
setValue |
(value: string[]) => void |
Function to set the value of the select |
clearValue |
(value?: string) => void |
Function to clear the value of the select. |
| If a value is provided, it will only clear that value, otherwise, it will clear all values. | ||
focus |
VoidFunction |
Function to focus on the select input |
getItemState |
(props: ItemProps) => ItemState |
Returns the state of a select item |
setOpen |
(open: boolean) => void |
Function to open or close the select |
collection |
ListCollection<V> |
Function to toggle the select |
reposition |
(options?: Partial<PositioningOptions>) => void |
Function to set the positioning options of the select |
multiple |
boolean |
Whether the select allows multiple selections |
disabled |
boolean |
Whether the select is disabled |
접근성 (Accessibility)
Listbox WAI-ARIA design pattern을 준수해요.
키보드 지원 (Keyboard Support)
Space
Description: When focus is on trigger, opens the select and focuses the first selected item.
When focus is on the content, selects the highlighted item.
Enter
Description: When focus is on trigger, opens the select and focuses the first selected item.
When focus is on content, selects the focused item.
ArrowDown
Description: When focus is on trigger, opens the select.
When focus is on content, moves focus to the next item.
ArrowUp
Description: When focus is on trigger, opens the select.
When focus is on content, moves focus to the previous item.
Esc
Description: Closes the select and moves focus to trigger.
A-Z + a-z
Description: When focus is on trigger, selects the item whose label starts with the typed character.
When focus is on the listbox, moves focus to the next item with a label that starts with the typed character.