Add close event to listbox #2593
Replies: 5 comments
-
Also really need this functionality! The contents of our |
Beta Was this translation helpful? Give feedback.
-
In case anyone finds this thread and still hopes to accomplish this outside of HeadlessUI, here's our solution. We use the Floating-UI library to help manage the position & existence of the floating (dropdown menu) element for the
Another possible solution would be to watch for the change of the |
Beta Was this translation helpful? Give feedback.
-
I hope this helps someone who is looking for a simple solution. I have a Listbox with a search inside of it, and I wanted to remove the search value when the Listbox closes. The Listbox will pass the open state to its children as props, so I added a wrapper component that received this open state and handled the rest.
Adding this solved my issue, but you can adapt to create your own onClose event if you want. I tested the performance, and it didn't affect my pages (they have multiple Listboxes) or the search. |
Beta Was this translation helpful? Give feedback.
-
If you want to keep it clean, you just need to set a ref, a ref in react is a function that has a element parameter - in this case the options container. Here you can set a state based on the element that ref provides. When options container is not visible it will be null (closed), and when opened it will return the html element (ul). Hope it helps. const [optionsContainerElement, setOptionsContainerElement] = React.useState(null);
React.useEffect(() => {
// ever you open/close options list
}, [optionsContainerElement]);
return (
<Listbox>
<Listbox.Button>my label</Listbox.Button>
<Listbox.Options ref={(node) => setOptionsContainerElement(node)}>
{options?.map((option) => (
<Listbox.Option value={option}>{option.label}</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
) |
Beta Was this translation helpful? Give feedback.
-
Unfort none of these worked for me. This worked though:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I've had the need for some way to tell when the listbox component closes, but there doesn't seem a way to tell as of now. Would it be possible to add a close event or something, that triggers whenever the listbox closes?
Example: I've got a listbox component with multiple set to
true
and I want to fetch some data from the selected options, but only the when the list is closed.Beta Was this translation helpful? Give feedback.
All reactions