'How to re-init the AlpineJS component after Livewire re-renders?

I have an alert component that I hide using AlpineJS but I want it to be visible again after Livewire re-renders.

Showing the alert using Livewire component

@if(Session::has('success'))
    <x-success-alert :message="Session::get('success')" />
@endif

AlpineJS component

<div x-data="{show: true}">
    <div x-show="show">
        <span>{{ $message }}</span>
        <button @click="show = false">&times;</button>
    </div>
</div>


Solution 1:[1]

The solution is to force Livewire to add that element in the dom again by adding wire:key to a random value.

<div wire:key="{{ rand() }}">
    <div x-data="{show: true}">
        <div x-show="show">
            <span>{{ $message }}</span>
            <button @click="show = false">&times;</button>
        </div>
    </div>
</div>

With that way, Livewire will destroy the old dom element and add the new one which re-init the Alpine component.

Solution 2:[2]

Just in case this helps anyone else, I have found that if an alpine component within a Livewire component is removed from the dom, it is not loaded correctly if reinstated *if the x-data directive is applied to the outermost element.

So, for example, just wrap the <x-success-alert> component in an additional div:

<div>
    <div x-data="{show: true}">
        <div x-show="show">
            <span>{{ $message }}</span>
            <button @click="show = false">&times;</button>
        </div>
    </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamed Abdallah
Solution 2 Alex Currie-Clark