diff --git a/src/autocomplete/use-autocomplete.ts b/src/autocomplete/use-autocomplete.ts index ecc1738..74f75c5 100644 --- a/src/autocomplete/use-autocomplete.ts +++ b/src/autocomplete/use-autocomplete.ts @@ -40,6 +40,7 @@ export interface Props extends Base { disabled?: boolean; onFocus?: (focused?: boolean) => void; preserveOrder?: boolean; + defaultIndex?: number; } export const useAutocomplete = ({ @@ -57,6 +58,7 @@ export const useAutocomplete = ({ keepOpened, keepQuery, preserveOrder, + defaultIndex, ...thru }: Props) => { const textual = useMemo( @@ -178,6 +180,8 @@ export const useAutocomplete = ({ (val: I | I[]) => meta.onChange(without(val)(meta.value) as I[]), [meta], ), + // whenever there is a query, override defaultIndex to 0, so the first result gets selected + defaultIndex: query?.length > 0 ? 0 : defaultIndex, }; }; diff --git a/src/listbox/use-items.ts b/src/listbox/use-items.ts index 80662e4..75840f1 100644 --- a/src/listbox/use-items.ts +++ b/src/listbox/use-items.ts @@ -24,8 +24,12 @@ export const useItems = ({ { length } = items; useEffect(() => { + // whenever the items list is empty, reset the position to defaultIndex setPosition({ - index: Math.min(position.index, items.length - 1), + index: + position.index < 0 + ? defaultIndex + : Math.min(position.index, items.length - 1), scroll: true, }); }, [items, defaultIndex]);