tailwindlabs / headlessui

Completely unstyled, fully accessible UI components, designed to integrate beautifully with Tailwind CSS.
https://headlessui.com
MIT License
25.85k stars 1.07k forks source link

Integrate Listbox (Select) with react hook form - onBlur issue #2936

Open faisalch10 opened 8 months ago

faisalch10 commented 8 months ago

What package within Headless UI are you using?

@headlessui/react

What version of that package are you using?

^1.7.18"

What browser are you using?

Chrome

Describe your issue

Hey, first of all thank for this amazing libaray. This is my first time of using it. I am facing the issue where react-hook-form onBlur event calling not properly. I added onBlur event on the root "ListBox" element but it didn't work as well as in nested components. onBlur event call soon as i click on the select box and thats weird.

https://github.com/tailwindlabs/headlessui/assets/57663488/04c035e9-34a3-4448-ad7c-5d0b2c5f696b

hyphast commented 6 months ago

You can add onBlur event to "Listbox.Options". I achieved the desired behavior this way:

    <Listbox 
      value={selectedPerson} 
      onChange={setSelectedPerson} 
      onMouseDown={(event) => {
        event.preventDefault();
      }}>
      <Listbox.Button>{selectedPerson.name}</Listbox.Button>
      <Listbox.Options onBlur={onBlur}>
        {people.map((person) => (
          <Listbox.Option
            key={person.id}
            value={person}
          >
            {person.name}
          </Listbox.Option>
        ))}
      </Listbox.Options>
    </Listbox>
mbrowne commented 5 months ago

@hyphast that seems to work if you're using the mouse but not the keyboard. It seems to work better to just wrap the entire Listbox with a div that has an onBlur prop:

        <div onBlur={onBlur}>
            <Listbox ...>
              ...
            </Listbox>
        </div>

Or alternatively you could put the <div onBlur={onBlur}> inside the <Listbox>.