Component to show message of action performed in Laravel Livewire

- Andrés Cruz

En español
Component to show message of action performed in Laravel Livewire

If you're using Livewire, you might be wondering how we can show a message for a few seconds and then hide it; this is particularly useful for when we do an insert, update, delete operation, the user is authenticated, etc; These messages are known as action carried out messages, they are not confirmation messages in Livewire as we saw before, since the user will not be able to cancel the action carried out, only a message will appear so that the user knows what action has just been carried out.

In Livewire you can implement these types of components very easily; but to get some inspiration, we have a component that is interesting to see, and it is:

https://github.com/laravel/jetstream/blob/2.x/resources/views/components/action-message.blade.php

Which with the help of Alpine.js, allows to determine the lifetime to display this piece of HTML:

<div x-data="{ shown: false, timeout: null }"
    x-init="@this.on('{{ $on }}', () => { clearTimeout(timeout); shown = true; timeout = setTimeout(() => { shown = false }, 2000);  })"
    x-show.transition.out.opacity.duration.1500ms="shown"
    x-transition:leave.opacity.duration.1500ms
    style="display: none;"
    {{ $attributes->merge(['class' => 'text-sm text-gray-600']) }}>
    {{ $slot->isEmpty() ? 'Saved.' : $slot }}
</div>

In practice we can create one based on the above as:

@if (session('status'))
    <div x-data="{ shown: false }"
        x-init="clearTimeout(2000); shown = true; timeout = setTimeout(() => { shown = false }, 2000);"
        x-show.transition.out.opacity.duration.1500ms="shown" x-transition:leave.opacity.duration.1500ms>
        <div class="p-1 mt-1 bg-purple-500 rounded-md">
            <x-card class="m-0">
                <h3 class="text-xl">
                    {{ session('status') }}
                </h3>
            </x-card>
        </div>
    </div>
@endif

The important thing is to use Alpine.js to hide the content by means of the setTimeout function after a certain time, otherwise, we already know how to show a completed action component that is displayed for a few seconds.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.