Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional onClose callback to Combobox component #3122

Merged
merged 3 commits into from
Apr 23, 2024

Conversation

RobinMalfait
Copy link
Member

@RobinMalfait RobinMalfait commented Apr 23, 2024

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>
    )
  }

Copy link

vercel bot commented Apr 23, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants