The dialog component informs users about a task and can contain critical information, require decisions, or involve multiple tasks. The Dialog component can be used to create a modal, alert, or other custom dialog and can be fully customized to fit your needs.
This component is based on the <dialog> HTML element. The following are the props that can be passed to the component.
Prop
Type
Default
hideClose
Whether or not the close button should be hidden.
boolean
false
triggerProps
Props to be passed to the trigger element.
object
—
variant
The variant the button will take. Corresponds to the design system.
"contained" | "outlined" | "subtle" | "text"
"contained"
size
The size of the button. Corresponds to the design system.
"sm" | "md" | "lg"
"md"
title
The title of the button. Used for screen readers and assistive tooltips
string
—
icon
Whether the button should be an icon only button or not. If `true`, the button will omit the text, become a 1:1 aspect ratio, and only display the icon.
boolean
false
href
The URL to link to. Passing in a value will cause the element to render as an anchor.
string
—
disabled
Whether the button is disabled or not.
boolean
false
Accessibility
The <Dialog> component leverages the <dialog> element which is natively accessible. The following are some additional accessibility features that are built into the component:
Clicking off from the dialog will close it. This is done by listening for a click event on the dialog element and checking if the target is the dialog itself.
When the dialog element is opened, the body prevents scrolling of the page. This is done by using x-trap.noscroll and having it track the open state of the dialog element.
This feature requires the Alpine.js Focus Plugin to be installed and configured in order to work.
When the dialog includes a form, we suggest passing autofocus to the first input field to ensure that the user can start interacting with the form immediately.
Ensure forms are validated before submitting. This can be done by adding the required attribute to the input fields and setting the formnovalidate attribute on the cancel button.
Examples
Hide Close Button
You can hide the default close button by passing the hideClose prop to the <Dialog> component.
The dialog element can be customized to fit whatever context it is being used in. The following example demonstrates how to create a custom trigger and dialog using the <Dialog> component. In addition, the dialog element uses a named slot of "trigger" for the content of the button. Any additional elements placed within the dialog will be rendered as the dialog content.
It’s recommended that an element like this is made as a reusable component. In this case, we have put together the following Astro component using Alpine.js to serve as a blueprint for how you could possibly set up a Dialog component, and what properties to consider.