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

Anchor elements with preventDefault as Tabs #3155

Closed lenzls closed 5 months ago

lenzls commented 6 months ago

What package within Headless UI are you using?

@headlessui/react

What version of that package are you using?

For example: 1.7.17

What browser are you using?

Firefox

Reproduction URL

https://codesandbox.io/p/devbox/hui-tabs-preventdefault-nmr95x

Describe your issue

I want to use anchor tags as Tabs in my application, since they actually point to a sensible URL. But I don't want them to actually redirect the page. In order to do that I added a e.preventDefault() click handler to the anchor tags.

In my mind this should prevent the redirect of the anchor tags, while still allowing the click event to bubble so that it can get handled appropriately by headless-ui.

In practise though, the click event prevents the redirect, but also leads to no tab change at all. Via keyboard controls, the tabs still work.

RobinMalfait commented 5 months ago

Hey!

This is the expected behavior, we run user provided event handlers before the internal ones, if the event is defaultPrevented then we won't continue with the internal function which we consider the default behavior for a <Tab /> click. This allows you to control some functionality such as not switching a <Tab />, or not closing a <Menu /> for example.

I want to use anchor tags as Tabs in my application, since they actually point to a sensible URL.

I wonder what benefit this has in practice especially since you are not actually redirecting in this case? I would recommend to not use an <a> in this case.

If you want to couple the <Tab /> and the URL and if you are using something like Next.js, then I would recommend to use the Link component which does perform a "redirect" (updates the URL), then I would recommend to control the tabs yourself (https://headlessui.com/react/tabs#controlling-the-selected-tab) and you can compute the selected index based on the current URL.

This would allow you to go to the second tab, refresh the browser and still end up in the second tab. You can also share the URL with somebody because the single source of truth for the active tab lives in the URL.

Would love to learn more about your use case!

Going to close this issue for now because it's the expected behavior. But if you can share more about your use case then we can maybe find another solution to your problem.

Hope this helps!