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

검색(Search)

원문 보기 위키 갱신

검색 상자 텍스트 입력과 메뉴를 함께 제공하는 검색 컴포넌트예요. 데이터셋 필터링이 콤보박스 컴포넌트 바깥에서 이루어져야 하는 경우를 처리해요.

출처: 문서

본문

Import

import { Search } from "@kobalte/core/search";
// or
import { Root, Label, ... } from "@kobalte/core/search";

Features

  • 결과 필터링(외부에서 관리해야 함)을 제외하고 콤보박스의 모든 기능을 상속해요.
  • 검색 제안 호출의 호출 빈도를 제한하기 위해 텍스트 입력을 디바운스(debounce)해요.
  • 제안이 로딩 중일 때 표시할 선택적 인디케이터를 제공해요.

Anatomy

검색은 다음 요소들로 구성돼요:

  • Search: 검색 컴포넌트의 루트 컨테이너예요.
  • Search.Label: 검색 컴포넌트에 대한 정보를 사용자에게 주는 라벨이에요.
  • Search.Description: 컴포넌트에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
  • Search.Control: 검색 입력과 인디케이터를 담아요.
  • Search.Indicator: 로딩 상태를 나타내는 아이콘을 감싸는 래퍼예요.
  • Search.Icon: 열 수 있다는 사실을 시각적으로 보여주기 위해 입력 옆에 자주 표시되는 작은 아이콘이에요.
  • Search.Input: 검색에 사용되며 선택된 제안 값을 반영하는 입력이에요.
  • Search.Portal: 검색이 열려 있을 때 자식 요소를 body로 포털해요.
  • Search.Content: 검색이 열려 있을 때 렌더링할 콘텐츠를 담아요.
  • Search.Arrow: 검색 콘텐츠 옆에 렌더링되는 선택적 화살표 요소예요.
  • Search.Listbox: 항목 목록을 담고 있으며 사용자가 그중 하나 이상을 검색할 수 있게 해줘요.
  • Search.Section: 옵션 그룹의 라벨을 렌더링하는 데 사용돼요. 화살표 키로 포커스할 수 없어요.
  • Search.Item: 검색 제안의 항목이에요.
  • Search.ItemLabel: 항목에 대해 발표되는 접근 가능한 라벨이에요.
  • Search.ItemDescription: 항목에 대해 발표되는 선택적 접근 가능한 설명이에요.
  • Search.NoResult: 제안 옵션이 주어지지 않았을 때 표시돼요.
<Search>
  <Search.Label />

  <Search.Control>
    <Search.Indicator>
      <Search.Icon />
    </Search.Indicator>
    <Search.Input />
  </Search.Control>

  <Search.Description />

  <Search.Portal>
    <Search.Content>
      <Search.Arrow />
      <Search.Listbox />
      <Search.NoResult>
    </Search.Content>
  </Search.Portal>
</Search>

Example

Usage

Debounce

debounceOptionsMillisecond를 설정해 입력이 변경될 때 즉시 새 검색 쿼리가 발생하지 않도록 해요. 대신 입력이 일정 시간 동안 유휴(idle) 상태가 되면 검색 쿼리가 요청돼요.

Search.Indicator에 loadingComponent를 추가해 디바운싱 아이콘을 표시할 수 있어요.

<Search
	triggerMode="focus"
	options={options()}
	onInputChange={query => setOptions(queryEmojiData(query))}
	onChange={result => setEmoji(result)}
	debounceOptionsMillisecond={300}
	optionValue="name"
	optionLabel="name"
	placeholder="Search an emoji…"
	itemComponent={(props: any) => (
		<Search.Item item={props.item}>
			<Search.ItemLabel>{props.item.rawValue.emoji}</Search.ItemLabel>
		</Search.Item>
	)}
>
	<Search.Control aria-label="Emoji">
		<Search.Indicator
			loadingComponent={
				<Search.Icon>
					<ReloadIcon />
				</Search.Icon>
			}
		>
			<Search.Icon>
				<MagnifyingGlassIcon />
			</Search.Icon>
		</Search.Indicator>
		<Search.Input />
	</Search.Control>
	<Search.Portal>
		<Search.Content onCloseAutoFocus={e => e.preventDefault()}>
			<Search.Listbox />
			<Search.NoResult>😬 No emoji found</Search.NoResult>
		</Search.Content>
	</Search.Portal>
</Search>

Inline style

명령 메뉴(command menu) 모양을 만들려면 open prop을 추가해 드롭다운을 항상 열어두세요. Search.Portal와 Search.Content를 div로 교체해 검색 입력 아래에 콘텐츠를 직접 마운트해요.

<Search
	open
	options={options()}
	onInputChange={query => setOptions(queryEmojiData(query))}
	onChange={result => setEmoji(result)}
	debounceOptionsMillisecond={300}
	optionValue="name"
	optionLabel="name"
	placeholder="Search an emoji…"
	itemComponent={(props: any) => (
		<Search.Item item={props.item}>
			<Search.ItemLabel>{props.item.rawValue.emoji}</Search.ItemLabel>
		</Search.Item>
	)}
>
	<Search.Control aria-label="Emoji">
		<Search.Indicator>
			<Search.Icon>
				<MagnifyingGlassIcon />
			</Search.Icon>
		</Search.Indicator>
		<Search.Input />
	</Search.Control>
	<div>
		<Search.Listbox />
		<Search.NoResult>😬 No emoji found</Search.NoResult>
	</div>
</Search>

API Reference

Search는 @kobalte/core/search의 Root import와 동일해요.

Prop Description
options Array<T | U>
An array of options to display as the available options.
optionValue keyof T | ((option: T) => string | number)
Property name or getter function to use as the value of an option. This is the value that will be submitted when the search component is part of a <form>.
optionTextValue keyof T | ((option: T) => string)
Property name or getter function to use as the text value of an option for typeahead purpose.
optionLabel keyof T | ((option: T) => string)
Property name or getter function to use as the label of an option. This is the string representation of the option to display in the Search.Input.
optionDisabled keyof T | ((option: T) => boolean)
Property name or getter function to use as the disabled flag of an option.
optionGroupChildren keyof U
Property name that refers to the children options of an option group.
itemComponent Component<SearchItemComponentProps<T>>
When NOT virtualized, the component to render as an item in the Search.Listbox.
sectionComponent Component<SearchSectionComponentProps<U>>
When NOT virtualized, the component to render as a section in the Search.Listbox.
multiple boolean
Whether the search component allows multi-selection.
placeholder JSX.Element
The content that will be rendered when no value or defaultValue is set.
value T | Array<T>
The controlled value of the search input.
defaultValue T | Array<T>
The value of the search input when initially rendered. Useful when you do not need to control the value.
onChange (value: T | Array<T>) => void
Event handler called when the value changes.
open boolean
The controlled open state of the search suggestion.
defaultOpen boolean
The default open state when initially rendered. Useful when you do not need to control the open state.
onOpenChange (open: boolean, triggerMode?: SearchTriggerMode) => void
Event handler called when the open state of the search component changes. Returns the new open state and the action that caused the opening of the menu.
onInputChange (value: string) => void
Handler that is called when the search input value changes.
triggerMode SearchTriggerMode
The interaction required to display search suggestion, it can be one of the following:
- input: open search suggestion when the user is typing.
- focus: open search suggestion when the input is focused.
- manual: open search suggestion when pressing arrow down/up while focus is on the input or clicking on the trigger.
removeOnBackspace boolean
When multiple is true, whether the last selected option should be removed when the user press the Backspace key and the input is empty.
allowDuplicateSelectionEvents boolean
Whether onChange should fire even if the new value is the same as the last.
disallowEmptySelection boolean
Whether the search component allows empty selection or not.
allowsEmptyCollection boolean
Whether the search component allows the menu to be open when the collection is empty.
closeOnSelection boolean
Whether the search component closes after selection.
selectionBehavior 'toggle' | 'replace'
How selection should behave in the search component.
virtualized boolean
Whether the search suggestion uses virtual scrolling.
modal boolean
Whether the search component should be the only visible content for screen readers, when set to true:
- interaction with outside elements will be disabled.
- scroll will be locked.
- focus will be locked inside the search component content.
- elements outside the search component content will not be visible for screen readers.
preventScroll boolean
Whether the scroll should be locked even if the search suggestion is not modal.
forceMount boolean
Used to force mounting the search suggestion (portal, positioner and content) when more control is needed. Useful when controlling animation with SolidJS animation libraries.
name string
The name of the search component. Submitted with its owning form as part of a name/value pair.
validationState 'valid' | 'invalid'
Whether the search component should display its "valid" or "invalid" visual styling.
required boolean
Whether the user must select an item before the owning form can be submitted.
disabled boolean
Whether the search component is disabled.
readOnly boolean
Whether the search component items can be selected but not changed by the user.
autoComplete string
Describes the type of autocomplete functionality the input should provide if any. See MDN
translations SearchIntlTranslations
Localization strings.

Search also accepts the following props to customize the placement of the Search.Content.

Prop Description
placement Placement
The placement of the search component content.
gutter number
The distance between the search component content and the trigger element.
shift number
The skidding of the search component content along the trigger element.
flip boolean | string
Controls the behavior of the search component content when it overflows the viewport:
- If a boolean, specifies whether the search component content should flip to the opposite side when it overflows.
- If a string, indicates the preferred fallback placements when it overflows.
The placements must be spaced-delimited, e.g. "top left".
slide boolean
Whether the search component content should slide when it overflows.
overlap boolean
Whether the search component content can overlap the trigger element when it overflows.
sameWidth boolean
Whether the search component content should have the same width as the trigger element. This will be exposed to CSS as --kb-popper-anchor-width.
fitViewport boolean
Whether the search component content should fit the viewport. If this is set to true, the search component content will have maxWidth and maxHeight set to the viewport size. This will be exposed to CSS as --kb-popper-available-width and --kb-popper-available-height.
hideWhenDetached boolean
Whether to hide the search component content when the trigger element becomes occluded.
detachedPadding number
The minimum padding in order to consider the trigger element occluded.
arrowPadding number
The minimum padding between the arrow and the search component content corner.
overflowPadding number
The minimum padding between the search component content and the viewport edge. This will be exposed to CSS as --kb-popper-overflow-padding.
Data attribute Description
data-valid Present when the search component is valid according to the validation rules.
data-invalid Present when the search component is invalid according to the validation rules.
data-required Present when the user must select an item before the owning form can be submitted.
data-disabled Present when the search component is disabled.
data-readonly Present when the search component is read only.

Search.Label, Search.Control, Search.Input, Search.Trigger, Search.Description and Search.ErrorMessage shares the same data-attributes.

Search.Control

Render Prop Description
selectedOptions Accessor<T[]>
An array of selected options.
remove (option: T) => void
A function to remove an option from the selection.
clear () => void
A function to clear the selection.

Search.Indicator

Prop Description
loadingComponent JSX.Element
The component that is displayed when suggestion options are being fetched.

Search.Icon

Data attribute Description
data-expanded Present when the search component is open.
data-closed Present when the search component is close.

Search.Content

Data attribute Description
data-expanded Present when the search component is open.
data-closed Present when the search component is close.

Search.Arrow

Prop Description
size number
The size of the arrow.

Search.Listbox

Prop Description
scrollRef Accessor<HTMLElement | undefined>
The ref attached to the scrollable element, used to provide automatic scrolling on item focus. If not provided, defaults to the listbox.
scrollToItem (key: string) => void
When virtualized, the Virtualizer function used to scroll to the item of the given key.
children (items: Accessor<Collection<CollectionNode<T | U>>>) => JSX.Element
When virtualized, a map function that receives an items signal representing all items and sections.

Search.Item

Prop Description
item CollectionNode
The collection node to render.
Data attribute Description
data-disabled Present when the item is disabled.
data-selected Present when the item is selected.
data-highlighted Present when the item is highlighted.

Search.ItemLabel and Search.ItemDescription shares the same data-attributes.

Rendered elements

Component Default rendered element
Search div
Search.Label span
Search.Description div
Search.Control div
Search.Indicator div
Search.Icon span
Search.Input input
Search.Portal Portal
Search.Content div
Search.Arrow div
Search.Listbox ul
Search.Section li
Search.Item li
Search.ItemLabel div
Search.ItemDescription div
Search.NoResult div

Accessibility

Keyboard Interactions

Key Description
Enter When focus is virtually on an item, selects the focused item.
ArrowDown When focus is on the input, opens the search suggestion and virtual focuses the first or selected item.
When focus is virtually on an item, moves virtual focus to the next item.
ArrowUp When focus is on the input, opens the search suggestion and virtual focuses the last or selected item.
When focus is virtually on an item, moves virtual focus to the previous item.
Alt + ArrowDown When focus is on the input, opens the search suggestion.
Alt + ArrowUp When focus is on the input, closes the search suggestion.
Home When focus is on the input, moves virtual focus to first item.
End When focus is on the input, moves virtual focus to last item.
Esc When the search suggestion is open, closes the search suggestion.
When the search suggestion is closed, clear the input and selection.

더 알아보기 (Learn more)