Resumen
UsaAlertDialog para una decisión que interrumpe el flujo de trabajo actual, como confirmar una eliminación. Proporciona semántica de alertdialog, gestión del foco y confirmación o cancelación explícitas.
Esta primitiva es para interfaces independientes de Twenty UI y controladas por el host. Los componentes Front deben solicitar una confirmación mediante la API de diálogo del host de SDK. Los Dialog, AlertDialog y cuadros de diálogo nativos del navegador directos están prohibidos dentro del renderizador de componentes frontales.
Uso
Estado no controlado.
UsadefaultOpen para establecer la visibilidad inicial. El cuadro de diálogo gestiona los cambios posteriores de su activador, controles de cierre e interacciones de descarte.
defaultOpen tiene como valor predeterminado false, por lo que se puede omitir. Este ejemplo utiliza una devolución de llamada de confirmación síncrona y se cierra después de que se ejecuta la acción.
Anatomía
Mantenga las partes relacionadas dentro deAlertDialog.Root o conecte los activadores separados mediante un identificador. Componga el portal, el fondo, el área de visualización y la ventana emergente por separado.
Establezca
container y keepMounted en Portal, atributos de fondo en Backdrop, atributos de diseño en Viewport, y las props size y de foco en Popup. Cada parte del elemento acepta sus propios atributos nativos, controladores, ref y composición render. Popup.ref apunta al elemento de contenido de la alerta. Title y Description establecen las relaciones accesibles; proporcione aria-label en Popup cuando omita un título.
La acción de confirmación es contenido de la aplicación, no una parte exportada. Usa Close con un controlador síncrono o un Button con estado abierto controlado para la confirmación asíncrona.
Estado controlado
Pasaopen y actualízalo con onOpenChange para gestionar la visibilidad del mismo cuadro de diálogo en el estado de React. La devolución de llamada recibe el valor booleano solicitado y los detalles del evento ascendente, incluidos reason, event y cancel(). Llame a eventDetails.cancel() para rechazar un cambio solicitado. onOpenChangeComplete se ejecuta después de que finalicen las transiciones de apertura o cierre.
Button con tu controlador de acciones en lugar de AlertDialog.Close. Mantén open en true mientras la acción está pendiente, llama a setOpen(false) después de que tenga éxito y muestra un error dentro del cuadro de diálogo si falla.
Componer con botones
Usarender para dar a los controles de activación y cierre el estilo de botón de Twenty UI. Las partes del cuadro de diálogo proporcionan sus controladores de interacción y referencias a los botones.
Button en tu propio componente, reenvía las propiedades y la referencia proporcionadas.
Activadores separados y acciones imperativas
Cree un identificador una vez conAlertDialog.createHandle\<Payload>() y páselo a handle en Root y en cada Trigger separado. El payload tipado de un activador está disponible para la función de renderizado secundaria de la raíz. Un identificador también admite open(triggerId), openWithPayload(payload), close() y el getter isOpen mientras su raíz está montada. Pase un ID de activador coincidente a open, o null para abrir sin un activador. Llame a métodos imperativos desde controladores de eventos o efectos.
Root.actionsRef expone close() y unmount(). Para una animación de cierre controlada externamente, llame a eventDetails.preventUnmountOnClose() en onOpenChange y, a continuación, llame a actionsRef.current?.unmount() después de que finalice la animación. Las partes con estilo normales gestionan sus propias transiciones sin estas acciones imperativas.
Tamaños y portales
Popup.size acepta sm, md, lg, xl y fullscreen, y el valor predeterminado es md. El tamaño y la apariencia pertenecen a la superficie de AlertDialog y no tienen que coincidir con los preajustes de Dialog.
Portal.container toma de forma predeterminada el contenedor del portal del tema más cercano. Sin uno, Base UI usa su destino de portal predeterminado, normalmente document.body. Un elemento explícito, una raíz sombreada o una ref anula ese destino. Un null explícito aplaza el montaje hasta que haya un contenedor disponible. Base UI resuelve una ref cuyo current es null mediante su destino predeterminado; use container={null} cuando el montaje deba esperar.
El contenido portalizado conserva el contexto del tema. Portal y Viewport heredan la dirección de texto proporcionada, a menos que establezca dir explícitamente. Establezca Portal.keepMounted para conservar el contenido montado y el estado del formulario mientras está cerrado.
Foco y cierre
La alerta atrapa el foco, bloquea la interacción externa y bloquea el desplazamiento de la página mientras está abierta. Escape solicita el cierre; hacer clic fuera no. Para evitar el descarte con Escape, cancele el cambioescape-key en onOpenChange. Proporciona siempre una acción visible de Cancelar o Cerrar.
De forma predeterminada, el foco se mueve al primer control que permite tabulación o a la ventana emergente en una apertura táctil. Coloque primero la acción menos destructiva o use Popup.initialFocus para seleccionarla. El foco vuelve al activador o al elemento que tenía el foco anteriormente cuando se cierra la alerta. Use Popup.finalFocus cuando una acción correcta elimine ese destino. Ambas props de foco aceptan un booleano, una ref de elemento o una devolución de llamada de tipo de interacción según el contrato ascendente.
”Props”
La referencia se genera a partir de los tipos de componentes públicos. Los atributos nativos, incluidos los nombres accesibles y los controladores de eventos, también se aceptan en las partes que renderizan elementos.AlertDialog.Root
RefObject<DialogRootActions | null>
A ref to imperative actions.
unmount: Ends the closing phase of the alert dialog after an externally controlled closing animation finishes. CallpreventUnmountOnClose()inonOpenChangefirst, otherwise the alert dialog completes closing on its own. Whether it leaves the DOM is decided bykeepMountedon the portal.close: Closes the alert dialog imperatively when called.
ReactNode | PayloadChildRenderFunction<Payload>
The content of the dialog.
This can be a regular React node or a render function that receives the
payload of the active trigger.boolean
predeterminado:"false"
Whether the dialog is initially open.To render a controlled dialog, use the
open prop instead.string | null
ID of the trigger that the dialog is associated with.
This is useful in conjunction with the
defaultOpen prop to create an initially open dialog.AlertDialogHandle<Payload>
A handle to associate the alert dialog with a trigger.
If specified, allows external triggers to control the alert dialog’s open state.
Can be created with the AlertDialog.createHandle() method.
((open: boolean, eventDetails: AlertDialogRootChangeEventDetails) => void)
Event handler called when the alert dialog is opened or closed.
((open: boolean) => void)
Event handler called after any animations complete when the dialog is opened or closed.
boolean
Whether the dialog is currently open.
string | null
ID of the trigger that the dialog is associated with.
This is useful in conjunction with the
open prop to create a controlled dialog.
There’s no need to specify this prop when the dialog is uncontrolled (that is, when the open prop is not set).AlertDialog.Trigger
string | ((state: DialogTriggerState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
AlertDialogHandle<Payload>
A handle to associate the trigger with an alert dialog.
Can be created with the AlertDialog.createHandle() method.
string
ID of the trigger. In addition to being forwarded to the rendered element,
it is also used to specify the active trigger for the dialog in controlled mode (with the DialogRoot
triggerId prop).boolean
predeterminado:"true"
Whether the component renders a native
<button> element when replacing it
via the render prop.
Set to false if the rendered element is not a button (for example, <div>).Payload
A payload to pass to the dialog when it is opened.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogTriggerState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogTriggerState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Portal
string | ((state: DialogPortalState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
HTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot | null> | null
Portal destination. Omission uses the theme container or Base UI default; explicit
null defers mounting. A ref with a null current value uses the Base UI default destination.boolean
predeterminado:"false"
Keeps content mounted while the alert is closed.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogPortalState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogPortalState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Backdrop
string | ((state: DialogBackdropState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
boolean
predeterminado:"false"
Whether the backdrop is forced to render even when nested.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogBackdropState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogBackdropState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Viewport
string | ((state: DialogViewportState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogViewportState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogViewportState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Popup
string | ((state: DialogPopupState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
boolean | RefObject<HTMLElement | null> | ((closeType: InteractionType) => boolean | void | HTMLElement | null)
Determines the element to focus when the dialog is closed.
false: Do not move focus.true: Move focus based on the default behavior (trigger or previously focused element).RefObject: Move focus to the ref element.function: Called with the interaction type (mouse,touch,pen, orkeyboard). Return an element to focus,trueto use the default behavior,nullto fall back to the default behavior, orfalse/undefinedto do nothing.
boolean | RefObject<HTMLElement | null> | ((openType: InteractionType) => boolean | void | HTMLElement | null)
Determines the element to focus when the dialog is opened.
By default, focus moves to the first tabbable element inside the popup, except when the dialog
is opened by touch — then the popup itself is focused to avoid opening the virtual keyboard.
false: Do not move focus.true: Move focus based on the default behavior (first tabbable element or popup).RefObject: Move focus to the ref element.function: Called with the interaction type (mouse,touch,pen, orkeyboard). Return an element to focus,trueto use the default behavior,nullto fall back to the default behavior, orfalse/undefinedto do nothing.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogPopupState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render."fullscreen" | "lg" | "md" | "sm" | "xl"
predeterminado:"md"
Width of the alert, or
fullscreen to fill the viewport.CSSProperties | ((state: DialogPopupState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Title
string | ((state: DialogTitleState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogTitleState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogTitleState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Description
string | ((state: DialogDescriptionState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogDescriptionState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogDescriptionState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Close
string | ((state: DialogCloseState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
boolean
predeterminado:"true"
Whether the component renders a native
<button> element when replacing it
via the render prop.
Set to false if the rendered element is not a button (for example, <div>).ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogCloseState>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.CSSProperties | ((state: DialogCloseState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
AlertDialog.Header
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.AlertDialog.Body
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.AlertDialog.Footer
Allows you to replace the component’s HTML element
with a different tag, or compose it with another component.Accepts a
ReactElement or a function that returns the element to render.