This episode is for members only

Sign up to access "Building Modals in Livewire" right now.

Get started
Already a member? Sign in to continue
05. Opening a modal from a modal


OK, let's take a look at how easy it is to trigger a second modal from another modal. So we just want to be able to open any modal from any modal.
Now, this is a lot easier than what we've done on our dashboard, because our dashboard isn't a LiveWire component. If your dashboard was a LiveWire component,
you could actually use this technique instead of relying on Alpine and the LiveWire global object to do this. So let's head over to our first modal.
I'm going to go ahead and wrap the content just here in a div, just to keep that separate. And we're going to create another div out here with a button, which is going to open the second modal.
Now, because we are working now within LiveWire, what we can do is just add a wire click event to this. And we can just directly call dispatch to. Now, we still want to give the name for this,
because obviously we are targeting a very specific modal. So we're going to say modals and second modal. And we are going to dispatch the show event.
That's going to get picked up within the second modal and hopefully show it. So let's head over and open up our first modal. And we've got our button here.
This still works, obviously, as normal. But when I click Open Second Modal, sure enough, that modal pops up. When I hit Close, that goes ahead and sets that modal
to not be visible. And of course, we see the other modal behind it. And we can just go ahead and close this off as normal. Now, there's one problem here.
If we open up our first modal and our second modal and we use the Escape key, that closes both of their modals off. Now, the reason for this is that our Escape key is a window
object that we press on our keyboard. And we can't target a specific element with this. So what that's going to do is it's going to fire this off and send that event
to both of the modals, technically, which will close both of them. So we can't really get around this unless we do some really, really, really hacky stuff.
But to be honest, it's not too bad. Most of the time, we're just going to go ahead and either close this or click outside. So there we go.
We have triggered a second modal from within another modal. And we can just keep doing this if we wanted to. So if we wanted to open a third modal from inside of our second modal, that would work as well.
11 episodes1 hr 1 min


Build your own modal functionality in Livewire, completely from scratch!

We’ll cover creating a re-usable modal wrapper, transitions, triggering modals from anywhere with our own Alpine functionality, trapping focus inside modals, layering modals correctly, and more.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!


No comments, yet. Be the first to leave a comment.