Emma Traversy
Emma Traversy

Reputation: 53

Alpinejs is not working for Modal only for Sidebar Menu

I am building a site with Laravel, tailwind css and alpinejs. I have a mobile navigation which is a offcanvas sidebar and a modal shopping cart. The responsive mobile menu works fine but I can not figure out why the modal is not showing:

Layout.blade.php which blade components are placed in :

<body class="bg-[#F8F3F0]" >
    <div x-data="{ open: false, opencart: false }" @keydown.window.escape="open = false">
        <x-home.cart />
        <x-home.mobilenav />

        <div class="w-full hexnoisegrad h-[700px]">
            ...
            <x-home.nav />
...

In the home.nav component we have buttons that trigger the menu and modal:

...
<button type="button"
        class=" ..."
        @click="open = true">
        <span class="sr-only">Open sidebar</span>
        <x-icon.menu />
</button>

<button type="button"
        class=" ..."
        @click="opencart = true">
        <span class="sr-only">Open Cart</span>
        <x-icon.bag/>
</button>

In the home.mobilenav component we have:

<div dir="rtl" x-show="open" class="fixed inset-0 flex z-40 lg:hidden"
  x-description="Off-canvas menu for mobile, show/hide based on off-canvas menu state." x-ref="dialog"
  aria-modal="true">
...

And finally in the home.cart (modal) component we have:

<div x-data="{ opencart: false }" @keydown.window.escape="opencart = false" x-show="opencart" class="fixed z-10 inset-0 overflow-y-auto" x-ref="dialog" aria-modal="true">
...

I don't know why but Menu works fine and Modal (Shopping Cart) is not! I think somehow it can not access "opencart" to check for the x-show. If I change the x-data of cart component to:

 x-data="{ opencart: true}"

Modal will open correctly for the first time but after closing the button won't make it appear again. I Also have drop downs that are working fine with alpine.

Very sorry for long post and taking your time. Thanks in advance.

Upvotes: 1

Views: 1108

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Alpinejs documentation indicates

Properties defined in an x-data directive are available to all element children. ref

That implies a parent/child relation between the elements holding x-data and x-show.

So try adding a wrapper div to hold x-data only.

<div x-data="{ opencart: false }">
  <div @keydown.window.escape="opencart = false" x-show="opencart" class="fixed z-10 inset-0 overflow-y-auto" x-ref="dialog" aria-modal="true">
  ...
</div>

Upvotes: 3

Related Questions