`Listbox` does not trigger a form's `onChange` when using React Hook Form's `Controller` (but native `select` does)
See original GitHub issueWhat package within Headless UI are you using?
@headlessui/react
What version of that package are you using?
v1.7.4
Reproduction URL
https://codesandbox.io/s/rhf-onchange-with-headlessuis-listbox-ce917d?file=/src/App.tsx
Describe your issue
I am not sure if this is a Headless UI issue, but this is my best guess.
Using the Listbox
together with React Hook Form does not fire the form’s onChange
.
Using a native select
with the same setup does fire the onChange
though, that’s why I created the issue here and not in the RHF repo.
In my reproduction you can see that the form is supposed to submit when the selection changes. Here, it logs to console, e.g.:
In the UI there are two selects: The first is via Listbox
, the second is with a native select
.
When selecting an entry via Listbox
, the value changes, but the form is not submitted (unexpected).
When selecting an entry via the native select
, the value changes and the form is submitted (as expected).
Code for reference, see CodeSandbox for full code:
function SelectNative({
selected,
onChange,
name
}: {
selected: string;
onChange: (newSelected: string) => void;
name: string;
}) {
return (
<select
value={selected}
onChange={(newSelected) => onChange(newSelected.currentTarget.value)}
name={name}
>
{people.map((person) => (
<option key={person.id} value={person.id}>
{person.name}
</option>
))}
</select>
);
}
function SelectWithListbox({
selected,
onChange,
name
}: {
selected: string;
onChange: (newSelected: string) => void;
name: string;
}) {
return (
<Listbox value={selected} onChange={onChange} name={name}>
<Listbox.Button>
{people.find((person) => person.id === selected)?.name}
</Listbox.Button>
<Listbox.Options>
{people.map((person) => (
<Listbox.Option key={person.id} value={person.id}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
);
}
Issue Analytics
- State:
- Created 10 months ago
- Reactions:3
- Comments:5 (1 by maintainers)
I have the same problem with
ComboBox
@alex-page the solution posted by @leapful works for the Combobox too.