Combobox
Un campo de texto con una lista de opciones filtrada. Selección simple o múltiple, elementos creables y búsqueda asíncrona.
NuevoInstalación
Copia y pega el siguiente código en tu proyecto.
1'use client';23import { motion, useReducedMotion } from 'motion/react';4import * as React from 'react';5import { createPortal } from 'react-dom';6import { cn } from '../lib/cn';7import { getNavigationIndex } from '../lib/collection';8import { FloatingPortal, useFloating } from '../lib/floating';9import { FormValue, useFormReset } from '../lib/form-control';10import { floatingOrigin, springs, still } from '../lib/motion';11import { useLayer } from '../lib/overlay';12import { useControllableState } from '../lib/use-controllable-state';1314type IconProps = React.SVGProps<SVGSVGElement> & {15 size?: number | string;16};1718function Icon({ size = 24, strokeWidth = 1.5, children, ...props }: IconProps) {19 return (20 <svg21 xmlns="http://www.w3.org/2000/svg"22 width={size}23 height={size}24 viewBox="0 0 24 24"25 fill="none"26 stroke="currentColor"27 strokeWidth={strokeWidth}28 strokeLinecap="round"29 strokeLinejoin="round"30 aria-hidden="true"31 {...props}32 >33 {children}34 </svg>35 );36}3738function CheckIcon(props: IconProps) {39 return (40 <Icon {...props}>41 <path d="m4 12.5 5 5L20 6.5" />42 </Icon>43 );44}4546function ChevronDownIcon(props: IconProps) {47 return (48 <Icon {...props}>49 <path d="m6 9 6 6 6-6" />50 </Icon>51 );52}5354function XIcon(props: IconProps) {55 return (56 <Icon {...props}>57 <path d="M18 6 6 18" />58 <path d="m6 6 12 12" />59 </Icon>60 );61}6263function PlusIcon(props: IconProps) {64 return (65 <Icon {...props}>66 <path d="M12 5v14" />67 <path d="M5 12h14" />68 </Icon>69 );70}7172function LoaderIcon(props: IconProps) {73 return (74 <Icon {...props}>75 <path d="M21.5 12A9.5 9.5 0 1 1 12 2.5" />76 </Icon>77 );78}7980type ComboboxFilter = (itemText: string, query: string) => boolean;8182type ComboboxCreateHandler = (query: string) => string | void;8384interface ComboboxBaseProps {85 children: React.ReactNode;86 inputValue?: string;87 defaultInputValue?: string;88 onInputValueChange?: (inputValue: string) => void;89 open?: boolean;90 defaultOpen?: boolean;91 onOpenChange?: (open: boolean) => void;92 filter?: ComboboxFilter | false;93 openOnFocus?: boolean;94 loading?: boolean;95 loadingLabel?: string;96 resultsLabel?: (count: number) => string;97 disabled?: boolean;98 name?: string;99 required?: boolean;100 form?: string;101 className?: string;102}103104interface ComboboxSingleProps {105 multiple?: false;106 value?: string;107 defaultValue?: string;108 onValueChange?: (value: string) => void;109}110111interface ComboboxMultipleProps {112 multiple: true;113 value?: string[];114 defaultValue?: string[];115 onValueChange?: (value: string[]) => void;116}117118type ComboboxProps = ComboboxBaseProps & (ComboboxSingleProps | ComboboxMultipleProps);119120interface ComboboxInputProps extends Omit<121 React.InputHTMLAttributes<HTMLInputElement>,122 'value' | 'defaultValue' | 'children' | 'size' | 'type'123> {124 children?: React.ReactNode;125 removeLabel?: (label: string) => string;126}127128interface ComboboxContentProps {129 children: React.ReactNode;130 className?: string;131 sideOffset?: number;132}133134interface ComboboxItemProps {135 value: string;136 children: React.ReactNode;137 textValue?: string;138 disabled?: boolean;139 className?: string;140}141142interface ComboboxGroupProps {143 children: React.ReactNode;144 className?: string;145}146147interface ComboboxLabelProps {148 children: React.ReactNode;149 className?: string;150}151152interface ComboboxSeparatorProps {153 className?: string;154}155156interface ComboboxEmptyProps {157 children: React.ReactNode;158 className?: string;159}160161interface ComboboxCreateProps {162 onCreate: ComboboxCreateHandler;163 children?: React.ReactNode | ((query: string) => React.ReactNode);164 className?: string;165}166167interface ComboboxClearProps {168 label?: string;169 className?: string;170}171172interface Registry {173 items: ReadonlyMap<string, string>;174 seen: ReadonlyMap<string, string>;175}176177interface ComboboxContextValue {178 multiple: boolean;179 disabled: boolean;180 openOnFocus: boolean;181 selectedValues: readonly string[];182 inputValue: string;183 query: string;184 expanded: boolean;185 loading: boolean;186 loadingLabel: string;187 registry: Registry;188 matches: (label: string) => boolean;189 createVisible: boolean;190 emptyVisible: boolean;191 highlightedKey: string | null;192 activeDescendant: string | undefined;193 canClear: boolean;194 inputId: string;195 listId: string;196 createId: string;197 optionId: (value: string) => string;198 inputRef: React.RefObject<HTMLInputElement | null>;199 fieldRef: React.RefObject<HTMLDivElement | null>;200 listRef: React.RefObject<HTMLDivElement | null>;201 layer: ReturnType<typeof useLayer>;202 setOpen: (open: boolean) => void;203 closeList: () => void;204 setActiveKey: (key: string | null) => void;205 activate: (key: string) => void;206 removeValue: (value: string) => void;207 clear: () => void;208 registerItem: (value: string, label: string) => () => void;209 registerCreate: (handler: ComboboxCreateHandler) => () => void;210 registerEmpty: () => () => void;211 onInputChange: (event: React.ChangeEvent<HTMLInputElement>) => void;212 onInputKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void;213 onInputFocus: () => void;214 onInputBlur: () => void;215 onInputClick: () => void;216}217218interface ComboboxGroupContextValue {219 labelId: string;220 registerLabel: () => () => void;221 registerValue: (value: string) => () => void;222}223224const CREATE_KEY = '\u0000create';225226const EMPTY: string[] = [];227228const ICON_VARIANTS = {229 open: { rotate: 180 },230 closed: { rotate: 0 },231} as const;232233const ICON_TRANSITION = springs.snappy;234const ICON_STYLE = { willChange: 'transform' } as const;235const CONTENT_STYLE = { willChange: 'opacity, transform' } as const;236237const CONTENT_OPEN = {238 opacity: 1,239 scale: 1,240 y: 0,241 visibility: 'visible' as const,242 transition: { ...springs.smooth, opacity: { duration: 0.15 } },243};244245const CONTENT_CLOSED = {246 bottom: {247 opacity: 0,248 scale: 0.97,249 y: -4,250 transition: { duration: 0.15 },251 transitionEnd: { visibility: 'hidden' as const },252 },253 top: {254 opacity: 0,255 scale: 0.97,256 y: 4,257 transition: { duration: 0.15 },258 transitionEnd: { visibility: 'hidden' as const },259 },260} as const;261262const ITEM_CLASS =263 'relative flex cursor-pointer items-center gap-2 rounded-sm py-1.5 ps-2 text-sm outline-none select-none transition-colors duration-150 data-highlighted:bg-muted';264265const ComboboxContext = React.createContext<ComboboxContextValue | null>(null);266267const ComboboxGroupContext = React.createContext<ComboboxGroupContextValue | null>(null);268269const ComboboxSlotContext = React.createContext<HTMLElement | null>(null);270271const useComboboxContext = (): ComboboxContextValue => {272 const context = React.use(ComboboxContext);273 if (!context) throw new Error('Combobox components must be used within Combobox');274 return context;275};276277function normalizeText(text: string) {278 return text.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();279}280281function defaultFilter(itemText: string, query: string) {282 return normalizeText(itemText).includes(normalizeText(query));283}284285function defaultResultsLabel(count: number) {286 if (count === 0) return 'No results';287 return count === 1 ? '1 result available' : `${count} results available`;288}289290function defaultRemoveLabel(label: string) {291 return `Remove ${label}`;292}293294function matchRange(text: string, query: string): [number, number] | null {295 const needle = normalizeText(query);296 if (!needle) return null;297 let folded = '';298 const starts: number[] = [];299 const ends: number[] = [];300 let index = 0;301 for (const char of text) {302 const piece = normalizeText(char);303 for (let step = 0; step < piece.length; step += 1) {304 starts.push(index);305 ends.push(index + char.length);306 }307 folded += piece;308 index += char.length;309 }310 const at = folded.indexOf(needle);311 if (at === -1) return null;312 const start = starts[at];313 const end = ends[at + needle.length - 1];314 if (start === undefined || end === undefined) return null;315 return [start, end];316}317318function highlightMatch(text: string, query: string): React.ReactNode {319 const range = matchRange(text, query);320 if (!range) return text;321 const [start, end] = range;322 return (323 <>324 {text.slice(0, start)}325 <mark data-slot="combobox-item-match" className="bg-transparent font-semibold text-current">326 {text.slice(start, end)}327 </mark>328 {text.slice(end)}329 </>330 );331}332333function getOptions(container: HTMLElement | null): HTMLElement[] {334 if (!container) return [];335 return Array.from(container.querySelectorAll<HTMLElement>('[role="option"]')).filter(336 (option) => option.getAttribute('aria-disabled') !== 'true' && !option.closest('[hidden]'),337 );338}339340function keyOf(option: HTMLElement): string | null {341 if (option.dataset.create !== undefined) return CREATE_KEY;342 return option.dataset.value ?? null;343}344345function toList(value: string | string[]): string[] {346 if (Array.isArray(value)) return value;347 return value ? [value] : EMPTY;348}349350function useClickOutside(351 ref: React.RefObject<HTMLElement | null>,352 anchorRef: React.RefObject<HTMLElement | null>,353 handler: () => void,354 enabled: boolean,355 isInsideUpperLayer: (target: EventTarget | null) => boolean,356) {357 React.useEffect(() => {358 if (!enabled) return;359 const handlePointerDownOutside = (event: PointerEvent) => {360 if (361 ref.current?.contains(event.target as Node) ||362 anchorRef.current?.contains(event.target as Node) ||363 isInsideUpperLayer(event.target)364 ) {365 return;366 }367 handler();368 };369 document.addEventListener('pointerdown', handlePointerDownOutside);370 return () => document.removeEventListener('pointerdown', handlePointerDownOutside);371 }, [ref, anchorRef, handler, enabled, isInsideUpperLayer]);372}373374const ComboboxRoot = (props: ComboboxProps): React.JSX.Element => {375 const {376 children,377 inputValue: controlledInputValue,378 defaultInputValue,379 onInputValueChange,380 open: controlledOpen,381 defaultOpen = false,382 onOpenChange,383 filter,384 openOnFocus = true,385 loading = false,386 loadingLabel = 'Searching...',387 resultsLabel = defaultResultsLabel,388 disabled = false,389 name,390 required,391 form,392 className,393 } = props;394 const multiple = props.multiple === true;395 const onValueChange = props.onValueChange as ((value: string | string[]) => void) | undefined;396 const [resetValue] = React.useState<string | string[]>(397 () => props.defaultValue ?? (multiple ? EMPTY : ''),398 );399400 const [value, setValue] = useControllableState<string | string[]>({401 value: props.value,402 defaultValue: resetValue,403 onChange: onValueChange,404 });405 const [inputValue, setInputValue] = useControllableState({406 value: controlledInputValue,407 defaultValue: defaultInputValue ?? '',408 onChange: onInputValueChange,409 });410 const [open, setOpenState] = useControllableState({411 value: controlledOpen,412 defaultValue: defaultOpen,413 onChange: onOpenChange,414 });415 const [registry, setRegistry] = React.useState<Registry>(() => ({416 items: new Map(),417 seen: new Map(),418 }));419 const [activeKey, setActiveKey] = React.useState<string | null>(null);420 const [createCount, setCreateCount] = React.useState(0);421 const [emptyCount, setEmptyCount] = React.useState(0);422 const [announcement, setAnnouncement] = React.useState('');423 const [trackedOpen, setTrackedOpen] = React.useState(open);424425 if (trackedOpen !== open) {426 setTrackedOpen(open);427 if (!open) setActiveKey(null);428 }429430 const createRef = React.useRef<ComboboxCreateHandler | null>(null);431 const dirtyRef = React.useRef(false);432 const rootRef = React.useRef<HTMLDivElement>(null);433 const inputRef = React.useRef<HTMLInputElement>(null);434 const fieldRef = React.useRef<HTMLDivElement>(null);435 const listRef = React.useRef<HTMLDivElement>(null);436437 const id = React.useId();438 const inputId = `combobox-input-${id}`;439 const listId = `combobox-list-${id}`;440 const createId = `${listId}-create`;441442 const selectedValues = React.useMemo(() => toList(value), [value]);443 const singleValue = typeof value === 'string' ? value : '';444 const selectedLabel = !multiple && singleValue ? registry.seen.get(singleValue) : undefined;445 const query =446 !multiple && selectedLabel !== undefined && inputValue === selectedLabel ? '' : inputValue;447 const trimmed = query.trim();448 const filterFn = filter === false ? null : (filter ?? defaultFilter);449450 const matches = React.useCallback(451 (label: string) => !filterFn || trimmed === '' || filterFn(label, trimmed),452 [filterFn, trimmed],453 );454455 const { visibleCount, exactMatch } = React.useMemo(() => {456 const needle = normalizeText(trimmed);457 let count = 0;458 let exact = false;459 for (const label of registry.items.values()) {460 if (matches(label)) count += 1;461 if (needle && normalizeText(label.trim()) === needle) exact = true;462 }463 return { visibleCount: count, exactMatch: exact };464 }, [registry.items, matches, trimmed]);465466 const createVisible = createCount > 0 && trimmed !== '' && !exactMatch;467 const emptyVisible = visibleCount === 0 && !loading && !createVisible;468 const expanded =469 open &&470 !disabled &&471 (visibleCount > 0 || createVisible || loading || (emptyCount > 0 && emptyVisible));472473 const layer = useLayer(expanded, false, listRef);474475 const activeLabel =476 activeKey === null || activeKey === CREATE_KEY ? undefined : registry.items.get(activeKey);477 const activeValid =478 activeKey === CREATE_KEY ? createVisible : activeLabel !== undefined && matches(activeLabel);479 const highlightedKey = expanded && activeValid ? activeKey : null;480481 const optionId = React.useCallback(482 (itemValue: string) => `${listId}-option-${encodeURIComponent(itemValue)}`,483 [listId],484 );485486 const activeDescendant =487 highlightedKey === null488 ? undefined489 : highlightedKey === CREATE_KEY490 ? createId491 : optionId(highlightedKey);492493 const setOpen = React.useCallback(494 (next: boolean) => {495 if (next && disabled) return;496 setOpenState(next);497 },498 [disabled, setOpenState],499 );500501 const closeList = React.useCallback(() => setOpenState(false), [setOpenState]);502503 const commitText = React.useCallback(504 (text: string) => {505 dirtyRef.current = false;506 setInputValue(text);507 },508 [setInputValue],509 );510511 const commitValue = React.useCallback(512 (next: string, label: string | undefined, toggle: boolean) => {513 if (multiple) {514 setValue((previous) => {515 const list = toList(previous);516 if (list.includes(next)) return toggle ? list.filter((item) => item !== next) : list;517 return [...list, next];518 });519 commitText('');520 return;521 }522 setValue(next);523 commitText(label ?? registry.seen.get(next) ?? next);524 closeList();525 },526 [multiple, setValue, commitText, closeList, registry.seen],527 );528529 const create = React.useCallback(() => {530 const handler = createRef.current;531 if (!handler || !trimmed) return;532 const created = handler(trimmed);533 setActiveKey(null);534 if (typeof created === 'string') {535 setRegistry((previous) => {536 if (previous.seen.has(created)) return previous;537 const seen = new Map(previous.seen);538 seen.set(created, trimmed);539 return { items: previous.items, seen };540 });541 commitValue(created, trimmed, false);542 return;543 }544 if (multiple) {545 commitText('');546 return;547 }548 commitText(trimmed);549 closeList();550 }, [trimmed, multiple, commitValue, commitText, closeList]);551552 const activate = React.useCallback(553 (key: string) => {554 if (key === CREATE_KEY) create();555 else commitValue(key, undefined, true);556 },557 [create, commitValue],558 );559560 const removeValue = React.useCallback(561 (item: string) => {562 setValue((previous) => {563 const list = toList(previous);564 return multiple ? list.filter((entry) => entry !== item) : '';565 });566 },567 [multiple, setValue],568 );569570 const clear = React.useCallback(() => {571 setValue(multiple ? EMPTY : '');572 commitText('');573 setActiveKey(null);574 }, [multiple, setValue, commitText]);575576 const registerItem = React.useCallback((itemValue: string, label: string) => {577 setRegistry((previous) => {578 if (previous.items.get(itemValue) === label && previous.seen.get(itemValue) === label) {579 return previous;580 }581 const items = new Map(previous.items);582 const seen = new Map(previous.seen);583 items.set(itemValue, label);584 seen.set(itemValue, label);585 return { items, seen };586 });587 return () => {588 setRegistry((previous) => {589 if (!previous.items.has(itemValue)) return previous;590 const items = new Map(previous.items);591 items.delete(itemValue);592 return { items, seen: previous.seen };593 });594 };595 }, []);596597 const registerCreate = React.useCallback((handler: ComboboxCreateHandler) => {598 createRef.current = handler;599 setCreateCount((count) => count + 1);600 return () => {601 if (createRef.current === handler) createRef.current = null;602 setCreateCount((count) => count - 1);603 };604 }, []);605606 const registerEmpty = React.useCallback(() => {607 setEmptyCount((count) => count + 1);608 return () => setEmptyCount((count) => count - 1);609 }, []);610611 const highlightOption = React.useCallback((option: HTMLElement | undefined) => {612 if (!option) return;613 setActiveKey(keyOf(option));614 option.scrollIntoView?.({ block: 'nearest' });615 }, []);616617 const onInputChange = React.useCallback(618 (event: React.ChangeEvent<HTMLInputElement>) => {619 dirtyRef.current = true;620 setInputValue(event.target.value);621 setActiveKey(null);622 if (!open) setOpen(true);623 },624 [setInputValue, open, setOpen],625 );626627 const onInputKeyDown = React.useCallback(628 (event: React.KeyboardEvent<HTMLInputElement>) => {629 if (event.nativeEvent.isComposing) return;630 switch (event.key) {631 case 'ArrowDown':632 case 'ArrowUp': {633 event.preventDefault();634 if (event.altKey) {635 setOpen(event.key === 'ArrowDown');636 return;637 }638 const options = getOptions(listRef.current);639 if (!expanded) setOpen(true);640 const current = expanded641 ? options.findIndex((option) => keyOf(option) === highlightedKey)642 : -1;643 const selected =644 current === -1 && !multiple && singleValue645 ? options.find((option) => option.dataset.value === singleValue)646 : undefined;647 if (selected) {648 highlightOption(selected);649 return;650 }651 const next = getNavigationIndex(event.key, current, options.length, {652 orientation: 'vertical',653 loop: true,654 });655 highlightOption(next === null ? undefined : options[next]);656 return;657 }658 case 'Enter': {659 if (!expanded) return;660 if (highlightedKey !== null) {661 event.preventDefault();662 activate(highlightedKey);663 return;664 }665 if (createVisible && visibleCount === 0) {666 event.preventDefault();667 create();668 }669 return;670 }671 case 'Escape': {672 if (expanded) {673 if (!layer.isTopmost()) return;674 event.preventDefault();675 closeList();676 return;677 }678 if (open) closeList();679 if (inputValue !== '' || (!multiple && singleValue !== '')) {680 event.preventDefault();681 clear();682 }683 return;684 }685 case 'Backspace': {686 const last = selectedValues[selectedValues.length - 1];687 if (multiple && inputValue === '' && last !== undefined) {688 event.preventDefault();689 removeValue(last);690 }691 return;692 }693 case 'Tab': {694 if (open) closeList();695 return;696 }697 }698 },699 [700 setOpen,701 expanded,702 multiple,703 singleValue,704 highlightOption,705 highlightedKey,706 activate,707 createVisible,708 visibleCount,709 create,710 layer,711 closeList,712 open,713 inputValue,714 clear,715 selectedValues,716 removeValue,717 ],718 );719720 const onInputFocus = React.useCallback(() => {721 if (openOnFocus) setOpen(true);722 }, [openOnFocus, setOpen]);723724 const onInputClick = React.useCallback(() => {725 if (openOnFocus && !open) setOpen(true);726 }, [openOnFocus, open, setOpen]);727728 const onInputBlur = React.useCallback(() => {729 closeList();730 if (multiple) {731 if (inputValue !== '') commitText('');732 return;733 }734 if (!dirtyRef.current) return;735 if (inputValue.trim() === '' && singleValue !== '') {736 setValue('');737 commitText('');738 return;739 }740 commitText(selectedLabel ?? '');741 }, [closeList, multiple, inputValue, singleValue, setValue, commitText, selectedLabel]);742743 const syncedLabelRef = React.useRef(selectedLabel);744745 React.useLayoutEffect(() => {746 if (multiple || syncedLabelRef.current === selectedLabel) return;747 syncedLabelRef.current = selectedLabel;748 if (!dirtyRef.current) setInputValue(selectedLabel ?? '');749 }, [multiple, selectedLabel, setInputValue]);750751 useFormReset(752 rootRef,753 () => {754 dirtyRef.current = false;755 setValue(resetValue);756 setOpenState(false);757 const label = typeof resetValue === 'string' ? registry.seen.get(resetValue) : undefined;758 setInputValue(label ?? defaultInputValue ?? '');759 },760 form,761 );762763 const message = !expanded ? '' : loading ? loadingLabel : resultsLabel(visibleCount);764765 React.useEffect(() => {766 const timer = setTimeout(() => setAnnouncement(message), message ? 500 : 0);767 return () => clearTimeout(timer);768 }, [message]);769770 const canClear = inputValue !== '' || selectedValues.length > 0;771772 const contextValue = React.useMemo<ComboboxContextValue>(773 () => ({774 multiple,775 disabled,776 openOnFocus,777 selectedValues,778 inputValue,779 query: trimmed,780 expanded,781 loading,782 loadingLabel,783 registry,784 matches,785 createVisible,786 emptyVisible,787 highlightedKey,788 activeDescendant,789 canClear,790 inputId,791 listId,792 createId,793 optionId,794 inputRef,795 fieldRef,796 listRef,797 layer,798 setOpen,799 closeList,800 setActiveKey,801 activate,802 removeValue,803 clear,804 registerItem,805 registerCreate,806 registerEmpty,807 onInputChange,808 onInputKeyDown,809 onInputFocus,810 onInputBlur,811 onInputClick,812 }),813 [814 multiple,815 disabled,816 openOnFocus,817 selectedValues,818 inputValue,819 trimmed,820 expanded,821 loading,822 loadingLabel,823 registry,824 matches,825 createVisible,826 emptyVisible,827 highlightedKey,828 activeDescendant,829 canClear,830 inputId,831 listId,832 createId,833 optionId,834 layer,835 setOpen,836 closeList,837 activate,838 removeValue,839 clear,840 registerItem,841 registerCreate,842 registerEmpty,843 onInputChange,844 onInputKeyDown,845 onInputFocus,846 onInputBlur,847 onInputClick,848 ],849 );850851 return (852 <ComboboxContext value={contextValue}>853 <div ref={rootRef} data-slot="combobox" className={cn('relative w-full', className)}>854 {children}855 <FormValue856 name={name}857 value={multiple ? selectedValues : singleValue}858 required={required}859 disabled={disabled}860 form={form}861 onFocus={() => inputRef.current?.focus()}862 />863 <span data-slot="combobox-status" aria-live="polite" aria-atomic="true" className="sr-only">864 {announcement}865 </span>866 </div>867 </ComboboxContext>868 );869};870871const ComboboxInput = ({872 className,873 children,874 placeholder,875 removeLabel = defaultRemoveLabel,876 id,877 onChange,878 onKeyDown,879 onFocus,880 onBlur,881 onClick,882 ref,883 ...props884}: ComboboxInputProps & { ref?: React.Ref<HTMLInputElement> }): React.JSX.Element => {885 const {886 multiple,887 disabled,888 openOnFocus,889 selectedValues,890 inputValue,891 expanded,892 registry,893 activeDescendant,894 inputId,895 listId,896 inputRef,897 fieldRef,898 setOpen,899 removeValue,900 onInputChange,901 onInputKeyDown,902 onInputFocus,903 onInputBlur,904 onInputClick,905 } = useComboboxContext();906907 React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);908909 React.useEffect(() => {910 const field = fieldRef.current;911 if (!field) return;912 const handleMouseDown = (event: MouseEvent) => {913 const input = inputRef.current;914 const target = event.target as Element;915 if (!input || disabled || target === input || target.closest('button')) return;916 event.preventDefault();917 const toggle = target.closest('[data-slot="combobox-chevron"]') !== null;918 const wasFocused = document.activeElement === input;919 input.focus();920 if (toggle) setOpen(!(expanded && wasFocused));921 else if (openOnFocus) setOpen(true);922 };923 field.addEventListener('mousedown', handleMouseDown);924 return () => field.removeEventListener('mousedown', handleMouseDown);925 }, [fieldRef, inputRef, disabled, expanded, openOnFocus, setOpen]);926927 const showPlaceholder = !multiple || selectedValues.length === 0;928929 return (930 <div931 ref={fieldRef}932 data-slot="combobox-field"933 data-state={expanded ? 'open' : 'closed'}934 data-disabled={disabled || undefined}935 className={cn(936 'text-foreground bg-secondary flex min-h-9 w-full cursor-text items-center gap-2 rounded-md px-3 text-sm transition-[color,box-shadow]',937 'hover:bg-muted',938 'focus-within:ring-ring focus-within:ring-2',939 'has-[input[aria-invalid=true]]:ring-destructive has-[input[aria-invalid=true]]:ring-2',940 'data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-disabled:opacity-40',941 className,942 )}943 >944 <div945 className={cn(946 'flex min-w-0 flex-1 flex-wrap items-center gap-1 self-stretch',947 multiple && selectedValues.length > 0 && 'py-1',948 )}949 >950 {multiple &&951 selectedValues.map((item) => {952 const label = registry.seen.get(item) ?? item;953 return (954 <span955 key={item}956 data-slot="combobox-chip"957 className="bg-secondary text-secondary-foreground inline-flex h-6 max-w-full items-center gap-1 rounded-full ps-2 pe-1 text-xs"958 >959 <span className="truncate">{label}</span>960 <button961 type="button"962 tabIndex={-1}963 aria-label={removeLabel(label)}964 data-slot="combobox-chip-remove"965 disabled={disabled}966 onMouseDown={(event) => event.preventDefault()}967 onClick={() => {968 removeValue(item);969 inputRef.current?.focus();970 }}971 className="text-muted-foreground hover:text-foreground hover:bg-muted focus-visible:ring-ring relative flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-full transition-colors outline-none before:absolute before:-inset-1.5 focus-visible:ring-2"972 >973 <XIcon size={12} className="size-3" />974 </button>975 </span>976 );977 })}978 <input979 {...props}980 ref={inputRef}981 id={id ?? inputId}982 type="text"983 role="combobox"984 aria-autocomplete="list"985 aria-haspopup="listbox"986 aria-expanded={expanded}987 aria-controls={expanded ? listId : undefined}988 aria-activedescendant={activeDescendant}989 autoComplete="off"990 autoCorrect="off"991 spellCheck={false}992 data-slot="combobox-input"993 disabled={disabled}994 value={inputValue}995 placeholder={showPlaceholder ? placeholder : undefined}996 onChange={(event) => {997 onChange?.(event);998 if (!event.defaultPrevented) onInputChange(event);999 }}1000 onKeyDown={(event) => {1001 onKeyDown?.(event);1002 if (!event.defaultPrevented) onInputKeyDown(event);1003 }}1004 onFocus={(event) => {1005 onFocus?.(event);1006 if (!event.defaultPrevented) onInputFocus();1007 }}1008 onBlur={(event) => {1009 onBlur?.(event);1010 onInputBlur();1011 }}1012 onClick={(event) => {1013 onClick?.(event);1014 if (!event.defaultPrevented) onInputClick();1015 }}1016 className={cn(1017 'placeholder:text-muted-foreground min-h-7 w-0 min-w-16 flex-1 self-stretch bg-transparent text-base outline-none disabled:cursor-not-allowed md:text-sm',1018 multiple && selectedValues.length > 0 && 'min-h-6',1019 )}1020 />1021 </div>1022 {children}1023 <motion.span1024 aria-hidden="true"1025 data-slot="combobox-chevron"1026 variants={ICON_VARIANTS}1027 animate={expanded ? 'open' : 'closed'}1028 transition={ICON_TRANSITION}1029 style={ICON_STYLE}1030 className="text-muted-foreground flex shrink-0 cursor-pointer"1031 >1032 <ChevronDownIcon size={16} className="size-4" />1033 </motion.span>1034 </div>1035 );1036};10371038const ComboboxClear = ({1039 label = 'Clear',1040 className,1041}: ComboboxClearProps): React.JSX.Element | null => {1042 const { canClear, clear, disabled, inputRef } = useComboboxContext();1043 if (!canClear) return null;1044 return (1045 <button1046 type="button"1047 tabIndex={-1}1048 aria-label={label}1049 data-slot="combobox-clear"1050 disabled={disabled}1051 onMouseDown={(event) => event.preventDefault()}1052 onClick={() => {1053 clear();1054 inputRef.current?.focus();1055 }}1056 className={cn(1057 'text-muted-foreground hover:text-foreground hover:bg-muted focus-visible:ring-ring relative flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm transition-colors outline-none before:absolute before:-inset-1.5 focus-visible:ring-2',1058 className,1059 )}1060 >1061 <XIcon size={14} className="size-3.5" />1062 </button>1063 );1064};10651066type ListboxName = { 'aria-labelledby': string } | { 'aria-label': string };10671068function listboxNameFor(input: HTMLInputElement | null, fallbackId: string): ListboxName {1069 if (!input) return { 'aria-labelledby': fallbackId };1070 const labelledBy = input.getAttribute('aria-labelledby');1071 if (labelledBy) return { 'aria-labelledby': labelledBy };1072 const label = input.getAttribute('aria-label') ?? input.labels?.[0]?.textContent?.trim();1073 if (label) return { 'aria-label': label };1074 return { 'aria-labelledby': input.id || fallbackId };1075}10761077const ComboboxContent = ({1078 children,1079 className,1080 sideOffset = 4,1081}: ComboboxContentProps): React.JSX.Element => {1082 const {1083 expanded,1084 closeList,1085 multiple,1086 loading,1087 loadingLabel,1088 listId,1089 inputId,1090 inputRef,1091 fieldRef,1092 listRef,1093 layer,1094 setActiveKey,1095 activate,1096 } = useComboboxContext();1097 const shouldReduceMotion = useReducedMotion();1098 const [name, setName] = React.useState<ListboxName>({ 'aria-labelledby': inputId });1099 const {1100 style: floatingStyle,1101 side,1102 anchorHidden,1103 anchorWidth,1104 } = useFloating({1105 open: expanded,1106 anchorRef: fieldRef,1107 floatingRef: listRef,1108 side: 'bottom',1109 align: 'start',1110 sideOffset,1111 });1112 const position = side === 'top' ? 'top' : 'bottom';1113 const anchorSeenRef = React.useRef(false);1114 const [emptySlot, setEmptySlot] = React.useState<HTMLDivElement | null>(null);11151116 useClickOutside(listRef, fieldRef, closeList, expanded, layer.isInsideUpperLayer);11171118 React.useLayoutEffect(() => {1119 setName(listboxNameFor(inputRef.current, inputId));1120 }, [expanded, inputRef, inputId]);11211122 React.useEffect(() => {1123 if (!expanded) {1124 anchorSeenRef.current = false;1125 return;1126 }1127 if (anchorWidth !== undefined && !anchorHidden) anchorSeenRef.current = true;1128 else if (anchorHidden && anchorSeenRef.current) closeList();1129 }, [expanded, anchorHidden, anchorWidth, closeList]);11301131 React.useEffect(() => {1132 const list = listRef.current;1133 if (!list || !expanded) return;1134 const optionFrom = (event: Event) => {1135 const option = (event.target as Element | null)?.closest<HTMLElement>('[role="option"]');1136 if (!option || option.getAttribute('aria-disabled') === 'true') return null;1137 return option;1138 };1139 const handleMove = (event: MouseEvent) => {1140 const option = optionFrom(event);1141 if (option) setActiveKey(keyOf(option));1142 };1143 const handleClick = (event: MouseEvent) => {1144 const option = optionFrom(event);1145 const key = option ? keyOf(option) : null;1146 if (key !== null) activate(key);1147 };1148 const handleMouseDown = (event: MouseEvent) => event.preventDefault();1149 list.addEventListener('mousedown', handleMouseDown);1150 list.addEventListener('mousemove', handleMove);1151 list.addEventListener('click', handleClick);1152 return () => {1153 list.removeEventListener('mousedown', handleMouseDown);1154 list.removeEventListener('mousemove', handleMove);1155 list.removeEventListener('click', handleClick);1156 };1157 }, [listRef, expanded, setActiveKey, activate]);11581159 const closedState = shouldReduceMotion1160 ? { ...CONTENT_CLOSED[position], scale: 1, y: 0, transition: still }1161 : CONTENT_CLOSED[position];11621163 const style = React.useMemo(1164 () => ({ ...floatingStyle, visibility: undefined, ...CONTENT_STYLE }),1165 [floatingStyle],1166 );11671168 return (1169 <FloatingPortal>1170 <motion.div1171 ref={listRef}1172 aria-hidden={!expanded}1173 data-slot="combobox-content"1174 data-state={expanded ? 'open' : 'closed'}1175 data-side={position}1176 initial={false}1177 animate={1178 expanded1179 ? shouldReduceMotion1180 ? { ...CONTENT_OPEN, transition: still }1181 : CONTENT_OPEN1182 : closedState1183 }1184 style={style}1185 className={cn(1186 'bg-popover text-popover-foreground z-500 max-h-[min(18rem,var(--available-height,18rem))] w-(--anchor-width) overflow-y-auto overscroll-contain rounded-md p-1 shadow-md outline-none',1187 floatingOrigin[position],1188 !expanded && 'pointer-events-none',1189 className,1190 )}1191 inert={!expanded}1192 >1193 {loading && (1194 <div1195 data-slot="combobox-loading"1196 className="text-muted-foreground flex items-center gap-2 px-2 py-1.5 text-sm"1197 >1198 <LoaderIcon1199 size={16}1200 className="size-4 animate-spin motion-reduce:[animation-duration:2.5s]"1201 />1202 {loadingLabel}1203 </div>1204 )}1205 <div ref={setEmptySlot} />1206 <div1207 id={listId}1208 role="listbox"1209 {...name}1210 aria-multiselectable={multiple || undefined}1211 data-slot="combobox-list"1212 className="flex flex-col outline-none"1213 >1214 <ComboboxSlotContext value={emptySlot}>{children}</ComboboxSlotContext>1215 </div>1216 </motion.div>1217 </FloatingPortal>1218 );1219};12201221const ComboboxItem = ({1222 value,1223 children,1224 textValue,1225 disabled = false,1226 className,1227}: ComboboxItemProps): React.JSX.Element => {1228 const { selectedValues, registry, matches, query, highlightedKey, optionId, registerItem } =1229 useComboboxContext();1230 const group = React.use(ComboboxGroupContext);1231 const registerGroupValue = group?.registerValue;1232 const itemRef = React.useRef<HTMLDivElement>(null);1233 const isSelected = selectedValues.includes(value);1234 const isHighlighted = highlightedKey === value;12351236 const staticLabel = textValue ?? (typeof children === 'string' ? children : undefined);12371238 React.useLayoutEffect(() => {1239 const label = staticLabel ?? itemRef.current?.textContent ?? '';1240 return registerItem(value, label.trim());1241 }, [value, staticLabel, registerItem]);12421243 React.useLayoutEffect(() => registerGroupValue?.(value), [registerGroupValue, value]);12441245 const label = staticLabel ?? registry.items.get(value) ?? '';1246 const visible = matches(label);12471248 return (1249 <div1250 ref={itemRef}1251 id={optionId(value)}1252 role="option"1253 aria-selected={isSelected}1254 aria-disabled={disabled || undefined}1255 hidden={!visible}1256 data-slot="combobox-item"1257 data-value={value}1258 data-selected={isSelected}1259 data-highlighted={isHighlighted || undefined}1260 data-disabled={disabled || undefined}1261 className={cn(1262 ITEM_CLASS,1263 'pe-8',1264 disabled && 'pointer-events-none opacity-40',1265 !visible && 'hidden',1266 className,1267 )}1268 >1269 <span className="flex-1 truncate">1270 {typeof children === 'string' ? highlightMatch(children, query) : children}1271 </span>1272 {isSelected && (1273 <span className="absolute end-2 flex items-center" aria-hidden="true">1274 <CheckIcon size={16} className="size-4" />1275 </span>1276 )}1277 </div>1278 );1279};12801281const ComboboxGroup = ({ children, className }: ComboboxGroupProps): React.JSX.Element => {1282 const { registry, matches } = useComboboxContext();1283 const labelId = React.useId();1284 const [labelCount, setLabelCount] = React.useState(0);1285 const [values, setValues] = React.useState<ReadonlySet<string>>(() => new Set());12861287 const registerLabel = React.useCallback(() => {1288 setLabelCount((count) => count + 1);1289 return () => setLabelCount((count) => count - 1);1290 }, []);12911292 const registerValue = React.useCallback((itemValue: string) => {1293 setValues((previous) => {1294 if (previous.has(itemValue)) return previous;1295 const next = new Set(previous);1296 next.add(itemValue);1297 return next;1298 });1299 return () => {1300 setValues((previous) => {1301 if (!previous.has(itemValue)) return previous;1302 const next = new Set(previous);1303 next.delete(itemValue);1304 return next;1305 });1306 };1307 }, []);13081309 const visible = Array.from(values).some((itemValue) => {1310 const label = registry.items.get(itemValue);1311 return label !== undefined && matches(label);1312 });13131314 const contextValue = React.useMemo(1315 () => ({ labelId, registerLabel, registerValue }),1316 [labelId, registerLabel, registerValue],1317 );13181319 return (1320 <ComboboxGroupContext value={contextValue}>1321 <div1322 role="group"1323 aria-labelledby={labelCount > 0 ? labelId : undefined}1324 hidden={!visible}1325 data-slot="combobox-group"1326 className={cn('flex flex-col', !visible && 'hidden', className)}1327 >1328 {children}1329 </div>1330 </ComboboxGroupContext>1331 );1332};13331334const ComboboxLabel = ({ children, className }: ComboboxLabelProps): React.JSX.Element => {1335 const group = React.use(ComboboxGroupContext);1336 const registerLabel = group?.registerLabel;13371338 React.useLayoutEffect(() => registerLabel?.(), [registerLabel]);13391340 return (1341 <div1342 id={group?.labelId}1343 role="presentation"1344 data-slot="combobox-label"1345 className={cn('text-muted-foreground px-2 py-1.5 text-xs font-medium', className)}1346 >1347 {children}1348 </div>1349 );1350};13511352const ComboboxSeparator = ({ className }: ComboboxSeparatorProps): React.JSX.Element | null => {1353 const { query } = useComboboxContext();1354 if (query) return null;1355 return (1356 <div1357 role="separator"1358 aria-orientation="horizontal"1359 data-slot="combobox-separator"1360 className={cn('bg-border/50 my-1 h-px', className)}1361 />1362 );1363};13641365const ComboboxEmpty = ({ children, className }: ComboboxEmptyProps): React.JSX.Element | null => {1366 const { emptyVisible, registerEmpty } = useComboboxContext();1367 const slot = React.use(ComboboxSlotContext);13681369 React.useLayoutEffect(() => registerEmpty(), [registerEmpty]);13701371 if (!emptyVisible || !slot) return null;13721373 return createPortal(1374 <div1375 data-slot="combobox-empty"1376 className={cn('text-muted-foreground px-2 py-6 text-center text-sm', className)}1377 >1378 {children}1379 </div>,1380 slot,1381 );1382};13831384const ComboboxCreate = ({1385 onCreate,1386 children,1387 className,1388}: ComboboxCreateProps): React.JSX.Element | null => {1389 const { createVisible, query, highlightedKey, createId, registerCreate } = useComboboxContext();1390 const onCreateRef = React.useRef(onCreate);13911392 React.useLayoutEffect(() => {1393 onCreateRef.current = onCreate;1394 });13951396 React.useLayoutEffect(1397 () => registerCreate((text: string) => onCreateRef.current(text)),1398 [registerCreate],1399 );14001401 if (!createVisible) return null;14021403 const isHighlighted = highlightedKey === CREATE_KEY;1404 const content =1405 typeof children === 'function' ? children(query) : (children ?? `Create "${query}"`);14061407 return (1408 <div1409 id={createId}1410 role="option"1411 aria-selected={false}1412 data-slot="combobox-create"1413 data-create=""1414 data-highlighted={isHighlighted || undefined}1415 className={cn(ITEM_CLASS, 'pe-2', className)}1416 >1417 <PlusIcon size={16} className="text-muted-foreground size-4 shrink-0" />1418 <span className="flex-1 truncate">{content}</span>1419 </div>1420 );1421};14221423const Combobox = Object.assign(ComboboxRoot, {1424 Input: ComboboxInput,1425 Content: ComboboxContent,1426 Item: ComboboxItem,1427 Group: ComboboxGroup,1428 Label: ComboboxLabel,1429 Separator: ComboboxSeparator,1430 Empty: ComboboxEmpty,1431 Create: ComboboxCreate,1432 Clear: ComboboxClear,1433});14341435export { Combobox };1436export type {1437 ComboboxClearProps,1438 ComboboxContentProps,1439 ComboboxCreateHandler,1440 ComboboxCreateProps,1441 ComboboxEmptyProps,1442 ComboboxFilter,1443 ComboboxGroupProps,1444 ComboboxInputProps,1445 ComboboxItemProps,1446 ComboboxLabelProps,1447 ComboboxProps,1448 ComboboxSeparatorProps,1449};
Actualiza las rutas de importación para que coincidan con la estructura de tu proyecto.
Anatomía
1import { Combobox } from '@/components/combobox';
1<Combobox>2 <Combobox.Input placeholder="Buscar framework" />3 <Combobox.Content>4 <Combobox.Empty>Sin resultados</Combobox.Empty>5 <Combobox.Item value="next">Next.js</Combobox.Item>6 <Combobox.Item value="astro">Astro</Combobox.Item>7 </Combobox.Content>8</Combobox>
Composición
Utiliza la siguiente composición para construir un
Combobox:Combobox├── Combobox.Input│ └── Combobox.Clear└── Combobox.Content├── Combobox.Empty├── Combobox.Group│ ├── Combobox.Label│ └── Combobox.Item├── Combobox.Separator└── Combobox.Create
Combobox.Input renderiza el campo entero: el input de texto, los chips en modo múltiple, lo que le pases como children (por ejemplo Combobox.Clear) y el chevron. Cada elemento registra su texto y la lista se filtra con eso mientras escribís. El filtro por defecto busca en cualquier parte del texto e ignora mayúsculas y acentos, así que cafe encuentra "Café". Pasá el tuyo con filter={(itemText, query) => boolean}.Los grupos sin elementos que coincidan se ocultan solos, los separadores se ocultan mientras hay una búsqueda y
Combobox.Empty aparece cuando nada coincide y no hay nada para crear.Variantes
Predeterminado (Default)
En modo simple el input muestra la etiqueta del elemento elegido. Escribir filtra la lista y, si salís sin elegir, el texto vuelve a la selección actual. Borrá el texto y salí para limpiar el valor.
Múltiple (Multiple)
Pasá
multiple y el valor pasa a ser un string[]. Los elementos elegidos aparecen como chips dentro del campo, la lista queda abierta después de cada elección y el texto se limpia para que sigas. Para quitar uno, hacé click de nuevo en el elemento, usá el botón del chip o apretá Backspace con el input vacío. Si queda texto sin elegir, se limpia cuando el input pierde el foco.Topics help people find your repository in search.
typescriptreact
1'use client';23import * as React from 'react';4import { Combobox } from '@/components/combobox';5import { Label } from '@/components/label';67const topics = [8 {9 label: 'Languages',10 items: [11 { value: 'typescript', label: 'TypeScript' },12 { value: 'rust', label: 'Rust' },13 { value: 'go', label: 'Go' },14 { value: 'python', label: 'Python' },15 ],16 },17 {18 label: 'Frontend',19 items: [20 { value: 'react', label: 'React' },21 { value: 'tailwindcss', label: 'Tailwind CSS' },22 { value: 'accessibility', label: 'Accessibility' },23 ],24 },25 {26 label: 'Infrastructure',27 items: [28 { value: 'postgres', label: 'Postgres' },29 { value: 'docker', label: 'Docker' },30 { value: 'edge', label: 'Edge functions' },31 ],32 },33];3435export function Multiple() {36 const [value, setValue] = React.useState(['typescript', 'react']);3738 return (39 <div className="flex w-full max-w-sm flex-col gap-1.5">40 <Label htmlFor="repo-topics" description="Topics help people find your repository in search.">41 Topics42 </Label>43 <Combobox multiple value={value} onValueChange={setValue}>44 <Combobox.Input45 id="repo-topics"46 placeholder="Add topics"47 aria-describedby="repo-topics-label-description"48 />49 <Combobox.Content>50 <Combobox.Empty>No topics match.</Combobox.Empty>51 {topics.map((group, index) => (52 <React.Fragment key={group.label}>53 {index > 0 && <Combobox.Separator />}54 <Combobox.Group>55 <Combobox.Label>{group.label}</Combobox.Label>56 {group.items.map((topic) => (57 <Combobox.Item key={topic.value} value={topic.value}>58 {topic.label}59 </Combobox.Item>60 ))}61 </Combobox.Group>62 </React.Fragment>63 ))}64 </Combobox.Content>65 </Combobox>66 </div>67 );68}
Creable (Creatable)
Combobox.Create aparece cuando hay texto y ningún elemento coincide exactamente. Llama a onCreate con el texto sin espacios de más. Devolvé el valor del elemento nuevo y queda seleccionado en el momento.bug
1'use client';23import * as React from 'react';4import { Combobox } from '@/components/combobox';5import { Label } from '@/components/label';67const initialLabels = [8 { value: 'bug', label: 'bug' },9 { value: 'feature', label: 'feature' },10 { value: 'docs', label: 'docs' },11 { value: 'good-first-issue', label: 'good first issue' },12 { value: 'needs-triage', label: 'needs triage' },13];1415function toSlug(text: string) {16 return text17 .toLowerCase()18 .replace(/[^a-z0-9]+/g, '-')19 .replace(/^-|-$/g, '');20}2122export function Creatable() {23 const [labels, setLabels] = React.useState(initialLabels);24 const [value, setValue] = React.useState(['bug']);2526 const createLabel = (name: string) => {27 const slug = toSlug(name) || name;28 setLabels((current) =>29 current.some((label) => label.value === slug)30 ? current31 : [...current, { value: slug, label: name }],32 );33 return slug;34 };3536 return (37 <div className="flex w-full max-w-sm flex-col gap-1.5">38 <Label htmlFor="issue-labels">Labels</Label>39 <Combobox multiple value={value} onValueChange={setValue}>40 <Combobox.Input id="issue-labels" placeholder="Find or create a label" />41 <Combobox.Content>42 {labels.map((label) => (43 <Combobox.Item key={label.value} value={label.value}>44 {label.label}45 </Combobox.Item>46 ))}47 <Combobox.Create onCreate={createLabel}>48 {(query) => `Create label "${query}"`}49 </Combobox.Create>50 </Combobox.Content>51 </Combobox>52 </div>53 );54}
1<Combobox.Create2 onCreate={(name) => {3 const value = toSlug(name);4 setLabels((labels) => [...labels, { value, label: name }]);5 return value;6 }}7>8 {(query) => `Crear etiqueta "${query}"`}9</Combobox.Create>
Asíncrono (Async)
Cuando los resultados vienen de un servidor, filtrá de tu lado. Poné
filter={false} para que el combobox muestre todos los elementos que renderices, controlá inputValue para saber qué buscar y pasá loading mientras corre la request. La lista muestra una fila con spinner y loadingLabel, y cuando llegan los resultados una región aria-live="polite" anuncia cuántos hay, medio segundo después del último cambio, así los lectores de pantalla no se saturan con cada tecla.1'use client';23import * as React from 'react';4import { Combobox } from '@/components/combobox';5import { Label } from '@/components/label';67const airports = [8 { code: 'EZE', city: 'Buenos Aires', country: 'Argentina' },9 { code: 'GRU', city: 'Sao Paulo', country: 'Brazil' },10 { code: 'SCL', city: 'Santiago', country: 'Chile' },11 { code: 'BOG', city: 'Bogota', country: 'Colombia' },12 { code: 'MEX', city: 'Mexico City', country: 'Mexico' },13 { code: 'JFK', city: 'New York', country: 'United States' },14 { code: 'SFO', city: 'San Francisco', country: 'United States' },15 { code: 'YYZ', city: 'Toronto', country: 'Canada' },16 { code: 'LHR', city: 'London', country: 'United Kingdom' },17 { code: 'MAD', city: 'Madrid', country: 'Spain' },18 { code: 'CDG', city: 'Paris', country: 'France' },19 { code: 'NRT', city: 'Tokyo', country: 'Japan' },20];2122type Airport = (typeof airports)[number];2324function searchAirports(query: string): Airport[] {25 const needle = query.trim().toLowerCase();26 if (!needle) return [];27 return airports.filter((airport) =>28 `${airport.city} (${airport.code}) ${airport.country}`.toLowerCase().includes(needle),29 );30}3132export function Async() {33 const [query, setQuery] = React.useState('');34 const [results, setResults] = React.useState<Airport[]>([]);35 const [loading, setLoading] = React.useState(false);3637 React.useEffect(() => {38 const timer = setTimeout(() => {39 setResults(searchAirports(query));40 setLoading(false);41 }, 450);42 return () => clearTimeout(timer);43 }, [query]);4445 const handleInputChange = (next: string) => {46 setQuery(next);47 setLoading(true);48 };4950 return (51 <div className="flex w-full max-w-sm flex-col gap-1.5">52 <Label htmlFor="destination">Destination</Label>53 <Combobox54 filter={false}55 loading={loading}56 inputValue={query}57 onInputValueChange={handleInputChange}58 >59 <Combobox.Input id="destination" placeholder="City or airport code">60 <Combobox.Clear />61 </Combobox.Input>62 <Combobox.Content>63 <Combobox.Empty>64 {query.trim() ? 'No airports found.' : 'Start typing to search airports.'}65 </Combobox.Empty>66 {results.map((airport) => (67 <Combobox.Item68 key={airport.code}69 value={airport.code}70 textValue={`${airport.city} (${airport.code})`}71 >72 <span className="flex w-full items-center justify-between gap-2">73 <span className="truncate">74 {airport.city}, {airport.country}75 </span>76 <span className="text-muted-foreground font-mono text-xs">{airport.code}</span>77 </span>78 </Combobox.Item>79 ))}80 </Combobox.Content>81 </Combobox>82 </div>83 );84}
1function AirportSearch() {2 const [query, setQuery] = React.useState('');3 const [results, setResults] = React.useState<Airport[]>([]);4 const [loading, setLoading] = React.useState(false);56 React.useEffect(() => {7 const controller = new AbortController();8 fetch(`/api/airports?q=${encodeURIComponent(query)}`, { signal: controller.signal })9 .then((response) => response.json())10 .then((data: Airport[]) => {11 setResults(data);12 setLoading(false);13 })14 .catch(() => undefined);15 return () => controller.abort();16 }, [query]);1718 return (19 <Combobox20 filter={false}21 loading={loading}22 loadingLabel="Buscando..."23 resultsLabel={(count) => (count === 1 ? '1 resultado' : `${count} resultados`)}24 inputValue={query}25 onInputValueChange={(next) => {26 setQuery(next);27 setLoading(true);28 }}29 >30 <Combobox.Input aria-label="Destino" placeholder="Ciudad o código de aeropuerto" />31 <Combobox.Content>32 <Combobox.Empty>No encontramos aeropuertos.</Combobox.Empty>33 {results.map((airport) => (34 <Combobox.Item key={airport.code} value={airport.code} textValue={airport.city}>35 {airport.city}, {airport.country}36 </Combobox.Item>37 ))}38 </Combobox.Content>39 </Combobox>40 );41}
Las etiquetas de los elementos elegidos se recuerdan, así que un chip o el input siguen mostrando el texto correcto aunque ese elemento ya no esté en los resultados.
Teclado
El foco nunca sale del input, así que estas teclas funcionan mientras escribís.
| Tecla | Acción |
|---|---|
| Escribir | Abre la lista y la filtra |
ArrowDown | Abre la lista, o pasa a la opción siguiente y vuelve al principio al llegar al final |
ArrowUp | Abre la lista en la última opción, o pasa a la anterior |
Alt + ArrowDown | Abre la lista sin mover la opción activa |
Alt + ArrowUp | Cierra la lista |
Enter | Elige la opción activa. Si Create es la única opción, crea el texto |
Escape | Cierra la lista. Con la lista cerrada, limpia el texto, y el valor en modo simple |
Home, End | Mueven el cursor del texto. La lista queda donde está |
Backspace | En modo múltiple, quita el último chip cuando el input está vacío |
Tab | Cierra la lista y sigue al próximo elemento |
En modo simple, las flechas arrancan en la opción seleccionada cuando todavía no hay ninguna activa.
Accesibilidad
El combobox sigue el patrón combobox de WAI-ARIA con un listbox emergente.
- El foco queda en el input. La persona está escribiendo, y mover el foco a la lista le sacaría el cursor y rompería la escritura, la selección de texto y los métodos de entrada (IME). El input conserva el foco y señala la opción activa con
aria-activedescendant, que los lectores de pantalla anuncian como si el foco se hubiera movido. Las opciones cancelan elmousedown, así que hacer click en una tampoco le saca el foco al input. - El input tiene
role="combobox",aria-autocomplete="list",aria-expandedy, mientras está abierto,aria-controls. Cada opción tiene un id estable armado conuseIdy su valor, másaria-selected. En modo múltiple el listbox llevaaria-multiselectable. - Nombrá el input con
aria-label,aria-labelledbyo un<label htmlFor>que apunte a suid. El listbox usa ese mismo nombre. - Los botones para quitar chips se anuncian como "Remove" más la etiqueta y quedan fuera del orden de tabulación, porque
Backspacecubre el caso del teclado. Cambiá el texto conremoveLabelenCombobox.Input. - Una región
aria-live="polite"anuncia la cantidad de resultados. Traducila conresultsLabelyloadingLabel. Combobox.Emptyy la fila de carga quedan fuera del listbox, así la lista solo contiene opciones y grupos.
Referencia de API
Combobox
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
multiple | boolean | false | Permite elegir varios elementos. El valor pasa a ser un string[] |
value | string | string[] | - | Valor controlado. Es un string[] cuando hay multiple |
defaultValue | string | string[] | '' o [] | Valor inicial cuando no es controlado |
onValueChange | (value: string | string[]) => void | - | Se llama cuando cambia el valor, con el mismo tipo que value |
inputValue | string | - | Texto controlado del input |
defaultInputValue | string | '' | Texto inicial cuando no es controlado |
onInputValueChange | (inputValue: string) => void | - | Se llama cuando cambia el texto, al escribir o después de elegir |
open | boolean | - | Estado de apertura controlado |
defaultOpen | boolean | false | Estado de apertura inicial cuando no es controlado |
onOpenChange | (open: boolean) => void | - | Se llama cuando cambia el estado de apertura |
filter | ((itemText: string, query: string) => boolean) | false | Contiene, sin mayúsculas ni acentos | Decide qué elementos coinciden. false muestra todos los elementos renderizados |
openOnFocus | boolean | true | Abre la lista cuando el input recibe foco o un click |
loading | boolean | false | Muestra una fila con spinner arriba de la lista |
loadingLabel | string | 'Searching...' | Texto de la fila de carga, que también se anuncia |
resultsLabel | (count: number) => string | - | Texto que se anuncia con la cantidad de resultados |
disabled | boolean | false | Deshabilita el input y los chips |
name | string | - | Renderiza inputs ocultos para que el valor se envíe con formularios, uno por elemento en múltiple |
required | boolean | - | Bloquea el envío del formulario hasta que se elija un valor |
form | string | - | Id de un formulario fuera del combobox al que pertenece el valor |
className | string | - | Clases CSS adicionales para el contenedor |
Combobox.Input
Acepta todos los atributos de
input, así que id, aria-label, aria-invalid y autoFocus van al input de texto.| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
placeholder | string | - | Se muestra cuando está vacío. En modo múltiple se oculta cuando hay chips |
removeLabel | (label: string) => string | Remove ... | Nombre accesible de cada botón para quitar un chip |
children | ReactNode | - | Se renderiza al final del campo, antes del chevron |
className | string | - | Clases CSS adicionales para el campo |
Combobox.Content
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
sideOffset | number | 4 | Separación entre el campo y la lista |
className | string | - | Clases CSS adicionales |
Combobox.Item
La opción activa recibe
data-highlighted, así podés darle estilo además del bg-muted por defecto.| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
value | string | - | Valor que se informa cuando se elige el elemento |
textValue | string | - | Texto para filtrar, para el input y para los chips cuando los children no son texto |
disabled | boolean | false | Lo salta en la navegación por teclado y bloquea elegirlo |
className | string | - | Clases CSS adicionales |
Combobox.Create
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
onCreate | (query: string) => string | void | - | Se llama con el texto recortado. Devolvé un valor para elegirlo |
children | ReactNode | ((query: string) => ReactNode) | Create "<query>" | Texto de la opción |
className | string | - | Clases CSS adicionales |
Combobox.Clear
Solo se renderiza cuando hay texto o un valor para limpiar.
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
label | string | 'Clear' | Nombre accesible del botón |
className | string | - | Clases CSS adicionales |
Combobox.Empty, Combobox.Group, Combobox.Label, Combobox.Separator
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
¿Encontraste algo que mejorar?
¿Notaste un error, tipografía o detalle faltante en esta página? Ayúdanos a mejorar la documentación abriendo un issue en GitHub.