How to use registers from react-hook-forms with Headless UI Combobox
P粉449281068
P粉449281068 2024-01-16 11:09:40
0
1
545

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粉449281068
P粉449281068

reply all(1)
P粉034571623

It's probably not a good idea to attach the react-hook-form handler directly to the Combobox.

  1. 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? !
    The
  1. 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.

  2. 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.

  3. Finally, in some other (non-HeadlessUI) Combobox implementations, the value will retain the original user input.

For example:

  1. User input: "United Airlines"
  2. Selection suggestions: "United States", "UK"...
  3. User selects an option
  4. 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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template