tailwindlabs / headlessui

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

Add optional `onClose` callback to `Combobox` component #3122

Closed RobinMalfait closed 6 months ago

RobinMalfait commented 6 months ago

This PR adds a new optional onClose prop to the Combobox component and it will be called when the Combobox closes.

Right now, we don't provide any information about why the Combobox closes, but that could be a future improvement.

A good use case for this prop is if you want to reset some state that was used to filter the options, instead of resetting the state in multiple places such as an onBlur on the ComboboxInput or the onChange of the Combobox component itself.

  import { Combobox } from '@headlessui/react'
  import { useState } from 'react'

  const people = [
    'Durward Reynolds',
    'Kenton Towne',
    'Therese Wunsch',
    'Benedict Kessler',
    'Katelyn Rohan',
  ]

  function MyCombobox() {
    const [selectedPerson, setSelectedPerson] = useState(people[0])
    const [query, setQuery] = useState('')

    const filteredPeople =
      query === ''
        ? people
        : people.filter((person) => {
            return person.toLowerCase().includes(query.toLowerCase())
          })

    return (
      <Combobox
        value={selectedPerson}
        onChange={setSelectedPerson}
+       onClose={() => {
+         setQuery('')
+       }}
      >
        <Combobox.Input onChange={(event) => setQuery(event.target.value)} />
        <Combobox.Options>
          {filteredPeople.map((person) => (
            <Combobox.Option key={person} value={person}>
              {person}
            </Combobox.Option>
          ))}
        </Combobox.Options>
      </Combobox>
    )
  }
vercel[bot] commented 6 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
headlessui-react ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 23, 2024 1:35pm
headlessui-vue ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 23, 2024 1:35pm