Home

1 minute read

Hide AlpineJS Components with x-cloak

Tony Lea

Hide AlpineJS Components with x-cloak

When using a javascript framework, you will most likely need a way to hide elements until they are fully rendered. This will reduce any flickering and it will create a better user experience.

With AlpineJS we can use the x-cloak attribute to hide elements. It works kind of like the invisibility cloak from Harry Potter. If you put it on, it will be hidden. 🧙

invisibility-cloak.png

When an Alpine component is finished rendering, it will check to see if the element has an attribute of x-cloak, and if so, that attribute will be removed.

In order to make use of that attribute, we can add the following CSS code to our website or application:

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

Now, all we have to do is add the x-cloak attribute to any element:

<div x-data="{ open: true }">
    <div x-show="open" x-cloak>
        Component Loaded!
    </div>
</div>

And that element will not be shown until the component has been loaded.

Here is a quick Codepen example without x-cloak: (you may need to click Rerun in the bottom-right to see it in action)

In the example above, the element we wanted to hide is still visible before the component has loaded.

✨ Summon the almighty cloak, and it will no longer be an issue, here is the same example using x-cloak:

That's how to hide an Alpine component until it has been loaded.

Be sure to head on over to the Alpine repo to learn more about all the cool things you can do with this awesome javascript library. ✌️