haveman
haveman

Reputation: 393

How to open Popover manually (Headless UI)

Hi im currently running an e-commerce site where i need to open the cart (popover component) manually whenever a person adds something to their cart.

This is the code i have at the moment, but it's not finished. Im using Headless UI from Tailwind.

  export default function Cart() {
  const {isCartOpen, openCart, closeCart} = useCartUI();
  const {lines, totalQuantity} = useCart();

  return (
    <Popover className="ml-4 flow-root text-sm lg:relative lg:ml-8">
      {({open}: {open: boolean}) => {
        if(!open) closeCart();
        return (
          <>
            <Popover.Button
              className={clsx(
                'flex h-[2.4rem] items-center rounded-sm bg-darkGray px-3 py-2 text-sm font-bold duration-150',
                open ? "bg-opacity-20" : "bg-opacity-0 hover:bg-opacity-10",
              )}
            >
              <span className="mr-2">Kurv</span>
              <ChevronDownIcon className={clsx(open && 'rotate-180')} />
            </Popover.Button>

            {isCartOpen && (
              <Popover.Panel static className="absolute inset-x-0 top-16 mt-px bg-white pb-6 shadow-lg sm:px-2 lg:top-full lg:left-auto lg:right-0 lg:mt-3 lg:-mr-1.5 lg:w-80 lg:rounded-lg lg:ring-1 lg:ring-black lg:ring-opacity-5">
                <CartHeader numLines={lines.length} />
                {totalQuantity === 0 ? (
                  <CartEmpty />
                ) : (
                  <>
                    <CartItems />
                    <CartFooter />
                  </>
                )}
              </Popover.Panel>
            )}   
          </>
        )
      }}
    </Popover>
  );
}

Upvotes: 3

Views: 5787

Answers (1)

erfling
erfling

Reputation: 409

I was just looking for a similar answer. If you haven't solved it, and are still interested, I found a solution.

You can use the static prop on the popover to always display it and use your own state, or the popover's internal state, to conditionally display its contents.

Here's an example https://codesandbox.io/s/d8llw?file=/src/App.js:600-609. You can find information on the static prop here: https://headlessui.com/react/popover#showing-hiding-the-popover

Upvotes: 2

Related Questions