Allow manual closing of dropdown for links with preventDefault or possibly asynchronous operations
See original GitHub issueWhat package within Headless UI are you using?
What version of that package are you using?
v1.6.6
What browser are you using?
N/A
Reproduction URL
https://github.com/agusterodin/headless-ui-dropdown-not-disappearing-after-click-bug-reproduction
Describe your issue
I am overriding a link’s behavior with event.preventDefault()
so that if the user clicks the link, logic runs to check if the user has any unsaved changes. Unfortunately, a recent update to Headless UI makes it so that the dropdown no longer disappears when clicking a link with event.preventDefault()
. I could just make this a button element instead so I don’t need event.preventDefault()
but then I no longer get “open in new tab” functionality and other benefits that come with using proper semantic HTML links.
I noticed that the popover component has a close
render prop for situations where you need to manually close the popover. Could we pretty please get a close
render prop for Dropdown.Item as well?
Thanks in advance. I absolutely love what you have built with the Tailwind ecosystem.
Issue Analytics
- State:
- Created a year ago
- Reactions:11
- Comments:13
Thanks for the issue and reproductions!
The issue: Headless UI will run its default behaviour, this means that whenever you click on a
Menu.Item
it will invoke whatever action is attached (invoke theonClick
of a button or go to the link in case of ana
) and then close theMenu
.However, we also have an escape hatch built-in where you can opt-out of default behaviour, in this case if you have an
onClick={e => e.preventDefault()}
then it won’t close the menu after it’s done invoking the attached action.This is a typical problem you see with tools like
Inertia
’sLink
component, because it intercepts the native browser action by runningevent.preventDefault()
so that your browser doesn’t make a full page refresh. Instead, it will intercept that, and use SPA-like routing to navigate you to the new spot.Due to this
event.preventDefault()
, it also means that the default behaviour of Headless UI is prevented.The solution: What we came up with is that we now expose a
close
function from theMenu
andMenu.Item
components’ render prop for React, and aclose
function from theMenu
andMenuItem
components slot prop for Vue.This will allow you to imperatively call the
close
function. For example, for Vue users it would look something like this:For React it is similar, but it is exposed from the render prop instead.
This should be fixed by #1897, and will be available in the next release.
You can already try it using:
npm install @headlessui/react@insiders
.npm install @headlessui/vue@insiders
.I also noticed this happening when an Inertia
Link
is used inside aMenuItem
after upgrading to 1.6.6 (seems to work in 1.6.5), due to thepreventDefault()