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> ); }
P粉0345716232024-01-17 10:36:15
It's probably not a good idea to attach the react-hook-form
handler directly to the Combobox
.
Input > onChange
will give you an event with the string target.value
instead of the Location/User/...
Model API. Would you issue a copy request in handleSubmit
to "unzip" it? And, if so, how would you handle API errors there? ! 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
to Combobox.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 the Combobox.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. Provide onChange
to Combobox
instead of Combobox.Input
. But this is only possible with the Controlled RHF API variant.