자동 완성 (Autocomplete)
Autocomplete는 셀렉트에 필터링을 결합해 사용자가 옵션 목록을 검색하고 선택할 수 있게 해주는 컴포넌트예요.
본문
사용 방법 (Usage)
import { Autocomplete, useFilter } from "@heroui/react";
{
"preview": "autocomplete-default"
}
구조 (Anatomy)
import {Autocomplete, Label, Description, SearchField, ListBox} from "@heroui/react";
export default () => (
<Autocomplete>
<Label />
<Autocomplete.Trigger>
<Autocomplete.Value />
<Autocomplete.ClearButton />
<Autocomplete.Indicator />
</Autocomplete.Trigger>
<Description />
<Autocomplete.Popover>
<Autocomplete.Filter>
<SearchField>
<SearchField.Group>
<SearchField.SearchIcon />
<SearchField.Input />
</SearchField.Group>
</SearchField>
<ListBox>
<ListBox.Item>
<Label />
<ListBox.ItemIndicator />
</ListBox.Item>
</ListBox>
</Autocomplete.Filter>
</Autocomplete.Popover>
</Autocomplete>
);
예제 (Examples)
변형 (Variants)
Autocomplete 컴포넌트는 두 가지 시각적 변형을 지원해요:
primary(기본값) - 그림자가 있는 표준 스타일로, 대부분의 사용 사례에 적합해요secondary- 그림자가 없는 낮은 강조 변형으로, Surface 컴포넌트에 적합해요
{
"preview": "autocomplete-variants"
}
전체 너비 (Full Width)
{
"preview": "autocomplete-full-width"
}
설명 포함 (With Description)
{
"preview": "autocomplete-with-description"
}
필수 (Required)
{
"preview": "autocomplete-required"
}
비활성 (Disabled)
{
"preview": "autocomplete-disabled"
}
비활성 옵션 포함 (With Disabled Options)
{
"preview": "autocomplete-with-disabled-options"
}
빈 컬렉션 허용 (Allows Empty Collection)
allowsEmptyCollection prop은 컬렉션에 항목이 없어도 자동 완성이 동작하게 해줘요. 목록이 처음에 비어 있을 수 있거나 모든 항목이 필터링되는 시나리오에 유용해요.
{
"preview": "autocomplete-allows-empty-collection"
}
섹션 포함 (With Sections)
{
"preview": "autocomplete-with-sections"
}
다중 선택 (Multiple Select)
{
"preview": "autocomplete-multiple-select"
}
경고: 다중 모드에서는 단순한
<Autocomplete.Value />가 각 선택 항목의ListBox.Itemchildren 복사본을 로케일 인식 구분자로 이어 붙여 트리거에 렌더링해요. 텍스트 전용 항목은 일반 텍스트로 읽히지만, 체크박스나 아바타 같은 시각적 콘텐츠는 선택 항목마다 한 번씩 나타나며 렌더 함수 children은 항상isSelected: false로 호출돼요.
선택한 값을 일반 텍스트로 표시하려면 각 선택 항목의 textValue를 로케일 인식 구분자로 이어 붙이는 selectedText 렌더 prop을 사용해요:
<Autocomplete.Value>
{({isPlaceholder, defaultChildren, selectedText}) =>
isPlaceholder ? defaultChildren : selectedText
}
</Autocomplete.Value>
제거 가능한 태그 같은 더 풍부한 레이아웃을 위해서는 위 예제처럼 state.selectedItems에서 직접 콘텐츠를 렌더링해요.
제어 (Controlled)
{
"preview": "autocomplete-controlled"
}
제어 다중 (Controlled Multiple)
{
"preview": "autocomplete-controlled-multiple"
}
제어된 열림 상태 (Controlled Open State)
{
"preview": "autocomplete-controlled-open-state"
}
비동기 필터링 (Asynchronous Filtering)
{
"preview": "autocomplete-asynchronous-filtering"
}
사용자 지정 표시기 (Custom Indicator)
{
"preview": "autocomplete-custom-indicator"
}
사용자 지정 값 (Custom Value)
렌더 props를 사용해 표시되는 값을 커스터마이징할 수 있어요:
{
"preview": "autocomplete-custom-value"
}
Surface에서 사용 (In Surface)
Surface 컴포넌트 안에서 사용할 때는 variant="secondary"를 사용해 표면 배경에 적합한 낮은 강조 변형을 적용해요.
{
"preview": "autocomplete-on-surface"
}
가상화 (Virtualization)
Autocomplete는 Virtualizer를 통해 가상화를 지원해요. 뷰포트 내에 보이는 행만 렌더링해 대용량 데이터셋을 효율적으로 렌더링할 수 있어요.
{
"preview": "autocomplete-virtualization"
}
고급 예제 (Advanced Examples)
사용자 선택 (User Selection)
{
"preview": "autocomplete-user-selection"
}
사용자 다중 선택 (User Selection Multiple)
{
"preview": "autocomplete-user-selection-multiple"
}
위치 검색 (Location Search)
{
"preview": "autocomplete-location-search"
}
태그 그룹 선택 (Tag Group Selection)
{
"preview": "autocomplete-tag-group-selection"
}
이메일 수신자 (Email Recipients)
{
"preview": "autocomplete-email-recipients"
}
커스터마이징 (Customization)
Tailwind CSS
{
"preview": "autocomplete-custom-styles"
}
글로벌 CSS (Global CSS)
Autocomplete 컴포넌트 클래스를 커스터마이징하려면 @layer components 지시문을 사용할 수 있어요.
@layer components {
.autocomplete {
@apply flex flex-col gap-1;
}
.autocomplete__trigger {
@apply rounded-lg border border-border bg-surface p-2;
}
.autocomplete__value {
@apply text-current;
}
.autocomplete__clear-button {
@apply text-muted hover:text-foreground;
}
.autocomplete__indicator {
@apply text-muted;
}
.autocomplete__popover {
@apply rounded-lg border border-border bg-surface p-2;
}
}
스타일 참조 (Styling Reference)
HeroUI는 컴포넌트 변형과 상태를 재사용하고 커스터마이징하기 쉽도록 BEM 방법론을 따르고 있어요.
CSS 클래스 (CSS Classes)
Autocomplete 컴포넌트는 다음 CSS 클래스를 사용해요 (소스 스타일 보기):
기본 클래스 (Base Classes)
.autocomplete- 기본 자동 완성 컨테이너.autocomplete__trigger- 자동 완성을 트리거하는 버튼.autocomplete__value- 표시되는 값 또는 플레이스홀더.autocomplete__clear-button- 선택한 값을 지우는 지우기 버튼.autocomplete__indicator- 드롭다운 표시기 아이콘.autocomplete__popover- 팝오버 컨테이너.autocomplete__filter- 필터 래퍼
변형 클래스 (Variant Classes)
.autocomplete--primary- 그림자가 있는 기본 변형 (기본값).autocomplete--secondary- 그림자가 없는 보조 변형, 표면에서 사용하기 적합해요
상태 클래스 (State Classes)
.autocomplete[data-invalid="true"]- 비정상 상태.autocomplete__trigger[data-focus-visible="true"]- 포커스된 트리거 상태.autocomplete__trigger[data-disabled="true"]- 비활성 트리거 상태.autocomplete__value[data-placeholder="true"]- 플레이스홀더 상태.autocomplete__clear-button[data-empty="true"]- 선택이 없을 때 숨겨지는 지우기 버튼.autocomplete__indicator[data-open="true"]- 열림 표시기 상태
인터랙티브 상태 (Interactive States)
이 컴포넌트는 유연성을 위해 CSS 의사 클래스와 데이터 속성을 모두 지원해요:
- 호버 (Hover): 트리거의
:hover또는[data-hovered="true"] - 포커스 (Focus): 트리거의
:focus-visible또는[data-focus-visible="true"] - 비활성 (Disabled): 자동 완성의
:disabled또는[data-disabled="true"] - 열림 (Open): 표시기의
[data-open="true"]
API 참조 (API Reference)
Autocomplete
| Prop | Type | Default | Description |
|---|---|---|---|
placeholder |
string |
'Select an item' |
Temporary text that occupies the autocomplete when it is empty |
selectionMode |
"single" | "multiple" |
"single" |
Whether single or multiple selection is enabled |
allowsEmptyCollection |
boolean |
false |
Whether the autocomplete allows an empty collection. When true, the autocomplete can function even with no items. |
isOpen |
boolean |
- | Sets the open state of the popover (controlled) |
defaultOpen |
boolean |
- | Sets the default open state of the popover (uncontrolled) |
onOpenChange |
(isOpen: boolean) => void |
- | Handler called when the open state changes |
disabledKeys |
Iterable<Key> |
- | Keys of disabled items |
isDisabled |
boolean |
- | Whether the autocomplete is disabled |
value |
Key | Key[] | null |
- | Current value (controlled) |
defaultValue |
Key | Key[] | null |
- | Default value (uncontrolled) |
onChange |
(value: Key | Key[] | null) => void |
- | Handler called when the value changes |
isRequired |
boolean |
- | Whether user input is required |
isInvalid |
boolean |
- | Whether the autocomplete value is invalid |
name |
string |
- | The name of the input, used when submitting an HTML form |
fullWidth |
boolean |
false |
Whether the autocomplete should take full width of its container |
variant |
"primary" | "secondary" |
"primary" |
Visual variant of the component. primary is the default style with shadow. secondary is a lower emphasis variant without shadow, suitable for use in surfaces. |
className |
string |
- | Additional CSS classes |
children |
ReactNode | RenderFunction |
- | Autocomplete content or render function |
Autocomplete.Trigger
| Prop | Type | Default | Description |
|---|---|---|---|
className |
string |
- | Additional CSS classes |
children |
ReactNode | RenderFunction |
- | Trigger content or render function |
Autocomplete.Value
| Prop | Type | Default | Description |
|---|---|---|---|
className |
string |
- | Additional CSS classes |
children |
ReactNode | RenderFunction |
- | Value content or render function |
Autocomplete.Indicator
| Prop | Type | Default | Description |
|---|---|---|---|
className |
string |
- | Additional CSS classes |
children |
ReactNode |
- | Custom indicator content |
Autocomplete.ClearButton
| Prop | Type | Default | Description |
|---|---|---|---|
className |
string |
- | Additional CSS classes |
onClick |
(e: MouseEvent) => void |
- | Handler called when button is clicked |
ref |
RefObject<HTMLButtonElement> |
- | Ref to the clear button element |
Autocomplete.Popover
| Prop | Type | Default | Description |
|---|---|---|---|
placement |
"bottom" | "bottom left" | "bottom right" | "bottom start" | "bottom end" | "top" | "top left" | "top right" | "top start" | "top end" | "left" | "left top" | "left bottom" | "start" | "start top" | "start bottom" | "right" | "right top" | "right bottom" | "end" | "end top" | "end bottom" |
"bottom" |
Placement of the popover relative to the trigger |
className |
string |
- | Additional CSS classes |
children |
ReactNode |
- | Content children |
Autocomplete.Filter
| Prop | Type | Default | Description |
|---|---|---|---|
filter |
(text: string, input: string) => boolean |
- | Custom filter function |
inputValue |
string |
- | Controlled input value |
onInputChange |
(value: string) => void |
- | Handler called when input value changes |
children |
ReactNode |
- | Filter content (SearchField and ListBox) |
useFilter 훅 (useFilter Hook)
React Aria의 useFilter 훅은 자동 완성 기능을 위한 필터링 함수를 제공해요.
import {useFilter} from "@heroui/react";
const {contains} = useFilter({sensitivity: "base"});
<Autocomplete.Filter filter={contains}>
<SearchField>...</SearchField>
<ListBox>...</ListBox>
</Autocomplete.Filter>
옵션 (Options):
| Option | Type | Default | Description |
|---|---|---|---|
sensitivity |
"base" | "accent" | "case" | "variant" |
"base" |
Locale sensitivity for matching |
반환 값 (Returns):
| Function | Type | Description |
|---|---|---|
contains |
(string: string, substring: string) => boolean |
Returns whether a string contains a given substring |
startsWith |
(string: string, substring: string) => boolean |
Returns whether a string starts with a given substring |
endsWith |
(string: string, substring: string) => boolean |
Returns whether a string ends with a given substring |
렌더 props (Render Props)
Autocomplete.Value에 렌더 함수를 사용할 때 다음 값이 제공돼요:
| Prop | Type | Description |
|---|---|---|
defaultChildren |
ReactNode |
The default rendered value. In multiple mode this is a copy of each selected item's children joined with locale-aware separators |
isPlaceholder |
boolean |
Whether the value is a placeholder |
state |
SelectState |
The state of the autocomplete. Use state.selectedItems for the selected collection nodes |
selectedItems |
(T | null)[] |
The values of the currently selected items |
selectedText |
string |
The textValue of the selected items joined with locale-aware separators |
접근성 (Accessibility)
Autocomplete 컴포넌트는 필터링이 포함된 ARIA select 패턴을 구현하며 다음을 제공해요:
- 완전한 키보드 내비게이션 지원
- 선택 변경에 대한 스크린 리더 알림
- 올바른 포커스 관리
- 비활성 상태 지원
- 필터링이 포함된 검색 기능
- HTML 폼 통합
자세한 내용은 React Aria Select 문서를 참고하세요.
더 알아보기 (Learn more)
HeroUI Autocomplete에 대해 더 알아보려면 공식 문서를 확인해 주세요.