Example with popper + portal + transition
See original GitHub issueCould we get an example of usage with popper and transition in portal?
This example is helpful: https://github.com/tailwindlabs/headlessui/blob/develop/packages/%40headlessui-react/pages/menu/menu-with-transition-and-popper.tsx
However, it doesn’t work when we put Portal into play. Just wrapping with Portal will either remove transitions or the dropdown will disappear after the transition depending on what you wrap inside of your Portal.
I kinda made it work (using their own hook) with code like this:
<Portal>
<Transition
show={isOpen}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-750"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
{(ref) => (
<div
ref={setPopperElement}
{...popperProps}
>
<div
ref={ref}
>
{children}
</div>
</div>
)}
</Transition>
</Portal>
It animates enter, but it fails to animate leave though. Also, this is only a custom dropdown element, it becomes even more complicated and fragile with Listbox or Menu. Similar approach worked for Menu, but for Listbox, even enter animations did not work until I added transform opacity-0 scale-95
to className for Listbox.Options in addition to Transition, which is super unintuitive.
Can we get a proper example? Maybe some errors will get fixed in the process too
Issue Analytics
- State:
- Created 3 years ago
- Comments:6
Ok, I figured it out. Here is a working example adapted from Transition+Menu example here:
https://codesandbox.io/s/headlessuireact-transitionmenupopper-example-forked-zl7zg
It is using the dev version of headlessui, because I needed callbacks for beforeEnter and afterLeave. I also used the official react-popper hook, as opposed to what other examples in headlessui use - you’d probably want to use an offical hook anyway.
Main changes are:
static
prop on listbox and menu items!The example might be simplified, but it’s a good working base for implementation. @RobinMalfait could be a good thing to add to docs
@vincaslt Thanks for the example.
Your example inspired me to create a package Headless UI Float, that can be easy to position floating Headless UI elements using Floating UI, support Transition & Portal.
The example below is a fork from your example, but replace Popper.js with my created package: https://codesandbox.io/s/headlessui-react-transition-menu-floating-ui-example-forked-sv28um?file=/src/App.js