How to prevent alpine.js modal from showing every time i refresh the page

Viewed 4667

i'm using alpine.js for my project and I have a modal that works well with alpine.js, my problem is that whenever you refresh the page, it shows for a second or two (while the page loads) and then goes away. I don't want to see it onload. Is there any way to workaround that in alpine.js?

My code

// Initialize data
<body x-data="{openModal: false}"
 :class="openModal ? 'overflow-hidden' : 'overflow-visible'"
>

// button
<button @click="openModal = true">
Open Modal
</button>
<!-- Modal -->
<div x-show="openModal">
<!-- content --> 
</div>
</body>
2 Answers

You're looking for the x-cloak directive.

It's a very simple one, it gets removed from the component when Alpine starts up.

So in your case you can add the following style (which will hide elements with the x-cloak attribute) and add x-cloak to your Alpine.js component (in this case the body).

<style>
[x-cloak] { display: none }
</style>
<body x-cloak x-data="{openModal: false}"
 :class="openModal ? 'overflow-hidden' : 'overflow-visible'"
>

// button
<button @click="openModal = true">
Open Modal
</button>
<!-- Modal -->
<div x-show="openModal">
<!-- content --> 
</div>
</body>

x-cloak is the right answear! But to be on the safe side in more cases, use the css important rule.

<style>
  [x-cloak] { 
      display: none !important;
   }
</style>
Related