fix(autocomplete): onClear (#5365)

* fix(autocomplete): add onClear

* feat(autocomplete): add test case for onClear

* chore(changeset): add changeset
This commit is contained in:
WK 2025-06-09 13:25:36 +08:00 committed by GitHub
parent ace931b44d
commit f1abe161b1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 30 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
"@heroui/autocomplete": patch
---
support onClear in Autocomplete (#5297)

View File

@ -811,6 +811,12 @@ properties to customize the popover, listbox and input components.
type: "() => void",
description: "Handler that is called when the Autocomplete's Popover is closed.",
default: "-"
},
{
attribute: "onClear",
type: "() => void",
description: "Handler that is called when the clear button is clicked.",
default: "-"
}
]}
/>

View File

@ -171,9 +171,16 @@ describe("Autocomplete", () => {
expect(autocomplete).toHaveFocus();
});
it("should clear value after clicking clear button", async () => {
it("should clear the value and onClear is triggered", async () => {
const onClear = jest.fn();
const wrapper = render(
<Autocomplete aria-label="Favorite Animal" data-testid="autocomplete" label="Favorite Animal">
<Autocomplete
aria-label="Favorite Animal"
data-testid="autocomplete"
label="Favorite Animal"
onClear={onClear}
>
<AutocompleteItem key="penguin">Penguin</AutocompleteItem>
<AutocompleteItem key="zebra">Zebra</AutocompleteItem>
<AutocompleteItem key="shark">Shark</AutocompleteItem>
@ -204,6 +211,9 @@ describe("Autocomplete", () => {
// click the clear button
await user.click(clearButton);
// onClear is triggered
expect(onClear).toHaveBeenCalledTimes(1);
// assert that the input has empty value
expect(autocomplete).toHaveValue("");

View File

@ -111,6 +111,11 @@ interface Props<T> extends Omit<HTMLHeroUIProps<"input">, keyof ComboBoxProps<T>
* Callback fired when the select menu is closed.
*/
onClose?: () => void;
/**
* Callback fired when the value is cleared.
* if you pass this prop, the clear button will be shown.
*/
onClear?: () => void;
/**
* Whether to enable virtualization of the listbox items.
* By default, virtualization is automatically enabled when the number of items is greater than 50.
@ -186,6 +191,7 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
errorMessage,
onOpenChange,
onClose,
onClear,
isReadOnly = false,
...otherProps
} = props;
@ -453,6 +459,7 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
}
state.setInputValue("");
state.open();
onClear?.();
},
"data-visible": !!state.selectedItem || state.inputValue?.length > 0,
className: slots.clearButton({