Renders a modal dialog for content such as forms and informational panels.
This component is appropriate for non-critical interactions. For dialogs
requiring immediate user response, such as confirmations or warnings, use
.alert_dialog/1
instead.
There are two primary ways to manage the display of the modal: via URL state
or by setting and removing the open
attribute.
To toggle the modal visibility based on the URL:
:if
attribute to conditionally render the modal when a specific
live action matches. on_cancel
attribute to patch back to the original URL when the
user chooses to close the modal. open
attribute to declare the modal’s initial visibility state. <.modal
:if={@live_action == :show}
id="pet-modal"
on_cancel={JS.patch(~p"/pets")}
open
>
<:title>Show pet</:title>
<p>My pet is called Johnny.</p>
<:footer>
<.link phx-click={JS.exec("data-cancel", to: "#pet-modal")}>
Close
</.link>
</:footer>
</.modal>
To open the modal, patch or navigate to the URL associated with the live action.
<.link patch={~p"/pets/#{@id}"}>show</.link>
To toggle the modal visibility dynamically with the open
attribute:
open
attribute in the template. show_modal/1
and hide_modal/1
functions to change the
visibility. <.modal id="pet-modal">
<:title>Show pet</:title>
<p>My pet is called Johnny.</p>
<:footer>
<.link phx-click={JS.exec("data-cancel", to: "#pet-modal")}>
Close
</.link>
</:footer>
</.modal>
To open modal, use the show_modal/1
function.
<.button
phx-click={Doggo.show_modal("pet-modal")}
aria-haspopup="dialog"
>
show
</.button>
To hide the modal when the open
attribute is not set, use the following CSS
styles:
dialog.modal:not([open]),
dialog.modal[open="false"] {
display: none;
}
While the showModal()
JavaScript function is typically recommended for
managing modal dialog semantics, this component utilizes the open
attribute
to control visibility. This approach is chosen to eliminate the need for
library consumers to add additional JavaScript code. To ensure proper
modal semantics, the aria-modal
attribute is added to the dialog element.