In this episode, we finally tackle a big issue: our modal opens just fine, but up to now, there's been no way to close it without refreshing the page! Obviously, that's not ideal. So, let's fix that by exploring three different methods to close the modal.
First, we make it so that clicking outside the modal (on the gray background overlay) will close it. This is a quick and easy win, using Alpine to react to clicks and set the visible
property to false
. We also talk briefly about why this solution needs to be improved when we get to layered modals later on, but for now it gets the job done.
Second, we add support for closing the modal with the Escape key. This involves listening for a global Escape keydown event and, again, setting visible
to false
. We discuss how this approach works and its benefits, but also mention that it closes all modals at once if multiple are open, which will need to be addressed in the future.
Third, we add the classic Close button right inside the modal's content. Clicking this button will close the modal just like the other methods. You can get fancy and style it as an 'X' if you like!
Throughout the episode, we look at how all these methods use Alpine's reactivity and Livewire's Entangle
feature to keep modal state consistent between the frontend and backend.
By the end of the video, we have a modal with three convenient ways to close it, and we get a sneak peek at challenges we'll solve later when we start layering modals.