I have this code and I'm trying to connect a Combobox component from Headless UI using react-hook-form. Whenever I try to enter different values and select different options, I get the error message -
Cannot read property of undefined (read 'name')
I tried a lot of different variations but couldn't get Combobox
to work with register
. Any help would be greatly appreciated. I want to use register
to do the job and don't want to use other Controller
methods to do react-hook-form
's methods.
import React from "react"; import { useState } from "react"; import { Combobox } from "@headlessui/react"; import { useForm } from "react-hook-form"; const people = [ { id: 1, name: "Durward Reynolds" }, { id: 2, name: "Kenton Towne" }, { id: 3, name: "Therese Wunsch" }, { id: 4, name: "Benedict Kessler" }, { id: 5, name: "Katelyn Rohan" }, ]; function Example() { const [query, setQuery] = useState(""); const filteredPeople = query === "" ? people : people.filter((person) => { return person.name.toLowerCase().includes(query.toLowerCase()); }); const { register, handleSubmit, setValue, formState: { errors }, } = useForm(); const submit = (data) => { console.log(JSON.stringify(data)); }; return ( <form onSubmit={handleSubmit(submit)}> <Combobox as="div" name="assignee" defaultValue={people[0]} {...register("assignee")} > <Combobox.Input onChange={(event) => setQuery(event.target.value)} displayValue={(person) => person.name} /> <Combobox.Options> {filteredPeople.map((person) => ( <Combobox.Option key={person.id} value={person}> {person.name} </Combobox.Option> ))} </Combobox.Options> </Combobox> <button>Submit</button> </form> ); } export default function check() { return ( <div> <Example /> </div> ); }
It's probably not a good idea to attach the
react-hook-form
handler directly to theCombobox
.Input > onChange
will give you an event with the stringtarget.value
instead of theLocation/User/...
Model API. Would you issue a copy request inhandleSubmit
to "unzip" it? And, if so, how would you handle API errors there? !The-
-
-
input may be related to an API error at the
Combobox
level. You must be extra careful to differentiate between "success" and "failure" strings at the form component level.Strings may not be parsed at the form component level. Especially in "Multiple" mode, you can present aggregated information in the input, such as "3 items were selected." If you expand
register
toCombobox.Input
, this will be your value.Finally, in some other (non-HeadlessUI)
Combobox
implementations, the value will retain the original user input.For example:
Combobox
takes the new value, but theCombobox.Input
value remains "United"You may want to stick with a portable and future-proof approach.
The conclusion is the same: let
Combobox
parse and convert the values for you. ProvideonChange
toCombobox
instead ofCombobox.Input
. But this is only possible with the Controlled RHF API variant.