fix(select): missing onChange when there are more than 300 items (#3598)

* fix(select): missing onChange when there are more than 300 items

* feat(select): add tests for onChange

* chore(changeset): add changeset
This commit is contained in:
աӄա 2024-09-11 11:23:48 +08:00 committed by GitHub
parent 446a6bf57c
commit 74792f7bff
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 80 additions and 7 deletions

View File

@ -0,0 +1,5 @@
---
"@nextui-org/select": patch
---
added missing onChange when there are more than 300 items (#3455)

View File

@ -652,6 +652,74 @@ describe("Select", () => {
// assert that the select listbox is closed
expect(select).toHaveAttribute("aria-expanded", "false");
});
it("should work with onChange (< 300 select items)", async () => {
const onChange = jest.fn();
let options = new Array(10).fill("");
options = options.map((_, i) => {
return `option ${i}`;
});
const wrapper = render(
<Select isOpen aria-label="Favorite Animal" label="Favorite Animal" onChange={onChange}>
{options.map((o) => (
<SelectItem key={o} value={o}>
{o}
</SelectItem>
))}
</Select>,
);
let listbox = wrapper.getByRole("listbox");
expect(listbox).toBeTruthy();
let listboxItems = wrapper.getAllByRole("option");
expect(listboxItems.length).toBe(10);
await act(async () => {
await user.click(listboxItems[1]);
expect(onChange).toBeCalledTimes(1);
});
});
it("should work with onChange (>= 300 select items)", async () => {
let onChange = jest.fn();
let options = new Array(300).fill("");
options = options.map((_, i) => {
return `option ${i}`;
});
const wrapper = render(
<Select isOpen aria-label="Favorite Animal" label="Favorite Animal" onChange={onChange}>
{options.map((o) => (
<SelectItem key={o} value={o}>
{o}
</SelectItem>
))}
</Select>,
);
let listbox = wrapper.getByRole("listbox");
expect(listbox).toBeTruthy();
let listboxItems = wrapper.getAllByRole("option");
expect(listboxItems.length).toBe(300);
await act(async () => {
await user.click(listboxItems[1]);
expect(onChange).toBeCalledTimes(1);
});
});
});
describe("Select with React Hook Form", () => {

View File

@ -249,16 +249,16 @@ export function useSelect<T extends object>(originalProps: UseSelectProps<T>) {
},
onSelectionChange: (keys) => {
onSelectionChange?.(keys);
if (onChange && typeof onChange === "function" && domRef.current) {
const event = {
if (onChange && typeof onChange === "function") {
onChange({
target: {
...domRef.current,
...(domRef.current && {
...domRef.current,
name: domRef.current.name,
}),
value: Array.from(keys).join(","),
name: domRef.current.name,
},
} as React.ChangeEvent<HTMLSelectElement>;
onChange(event);
} as React.ChangeEvent<HTMLSelectElement>);
}
},
});