11

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>
codemebro
  • 133
  • 2
  • 8

3 Answers3

20

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>
Hugo
  • 3,500
  • 1
  • 14
  • 28
10

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>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
2

Apart from the x-clock solution, another solution is to wrap the content you want to control in a <template> tag with an x-if="true" parameter.
Check the code below.

<template x-if="true">
  <div x-show="openModal">
    <!-- content --> 
  </div>
</template>

This works because <template> elements are "hidden" in browsers by default, you won't see the <div> until Alpine has had a chance to render the x-if="true" and show it as the docs describe here

Allan Dereal
  • 113
  • 2
  • 5