Skip to content

Commit 7c2bc4a

Browse files
authored
fix(autocomplete): clear autocomplete value when pressing clear button (#4458)
1 parent 16c57ec commit 7c2bc4a

File tree

3 files changed

+49
-5
lines changed

3 files changed

+49
-5
lines changed

.changeset/nice-books-yell.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@nextui-org/autocomplete": patch
3+
---
4+
5+
clear autocomplete value when pressing clear button (#4402)

packages/components/autocomplete/__tests__/autocomplete.test.tsx

+43
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,49 @@ describe("Autocomplete", () => {
235235
expect(autocomplete).toHaveFocus();
236236
});
237237

238+
it("should clear arbitrary value after clicking clear button", async () => {
239+
const wrapper = render(
240+
<Autocomplete aria-label="Favorite Animal" data-testid="autocomplete" label="Favorite Animal">
241+
<AutocompleteItem key="penguin" value="penguin">
242+
Penguin
243+
</AutocompleteItem>
244+
<AutocompleteItem key="zebra" value="zebra">
245+
Zebra
246+
</AutocompleteItem>
247+
<AutocompleteItem key="shark" value="shark">
248+
Shark
249+
</AutocompleteItem>
250+
</Autocomplete>,
251+
);
252+
253+
const autocomplete = wrapper.getByTestId("autocomplete");
254+
255+
// open the select listbox
256+
await user.click(autocomplete);
257+
258+
// assert that the autocomplete listbox is open
259+
expect(autocomplete).toHaveAttribute("aria-expanded", "true");
260+
261+
await user.keyboard("pe");
262+
263+
const {container} = wrapper;
264+
265+
const clearButton = container.querySelector(
266+
"[data-slot='inner-wrapper'] button:nth-of-type(1)",
267+
)!;
268+
269+
expect(clearButton).not.toBeNull();
270+
271+
// click the clear button
272+
await user.click(clearButton);
273+
274+
// assert that the input has empty value
275+
expect(autocomplete).toHaveValue("");
276+
277+
// assert that input is focused
278+
expect(autocomplete).toHaveFocus();
279+
});
280+
238281
it("should keep the ListBox open after clicking clear button", async () => {
239282
const wrapper = render(
240283
<Autocomplete aria-label="Favorite Animal" data-testid="autocomplete" label="Favorite Animal">

packages/components/autocomplete/src/use-autocomplete.ts

+1-5
Original file line numberDiff line numberDiff line change
@@ -418,13 +418,9 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
418418
onPress: (e: PressEvent) => {
419419
slotsProps.clearButtonProps?.onPress?.(e);
420420
if (state.selectedItem) {
421-
state.setInputValue("");
422421
state.setSelectedKey(null);
423-
} else {
424-
if (allowsCustomValue) {
425-
state.setInputValue("");
426-
}
427422
}
423+
state.setInputValue("");
428424
state.open();
429425
},
430426
"data-visible": !!state.selectedItem || state.inputValue?.length > 0,

0 commit comments

Comments
 (0)