Let's get started by quickly writing both the HTML and CSS for a basic modal. It won't be perfect, but this should be enough to get us going. We'll use Tailwind to quickly apply the necessary classes.
Now that we have the beginnings of a modal, let's extract all of that HTML into a Blade component. Once complete, it only takes a few characters to add Alpine support.
Before we review Livewire integration, let's first learn how to use the URI hash as a technique for toggling the display of any modal on your site.
In this episode, we'll use Alpine to intercept the submission of a form, and then display a confirmation modal to the user.
In its current form, our modal is missing a number of expected features. For example, when I click outside of the modal card, it should close. If I press the
escape key, it should also close. These are basic conveniences that any modal should provide. As we solve this problem, we'll have the opportunity to review Livewire's
@entangle directive which will allow us to synchronize a property's value between Livewire And Alpine. If its value changes on one end, the other will update as well.
Let's set aside five minutes to quickly improve the design and flow of our modal. In particular, we'll combine Alpine and Tailwind to quickly apply a nice-enough looking scale and fade transition to the modal card, itself.
If you need to toggle an Alpine modal from anywhere in your application, it might be useful to reach for an event-based approach. In this lesson, we'll add a
$modals.show('modal-name') API for activating any registered modal. To allow for this, we'll dispatch an event on the
window object, and then listen for it from our modal Blade component.