Resumen
UsaDialog para formularios, detalles y otras tareas que se abren sobre la página. Gestiona el foco, el cierre con el teclado, los clics fuera y el desplazamiento. Usa AlertDialog cuando el usuario debe responder explícitamente a una decisión.
Esta API es para Twenty UI independiente y la aplicación host de Twenty. Los componentes front deben usar openCommandConfirmationModal del SDK en lugar de renderizar Dialog o AlertDialog directamente. Los diálogos nativos del navegador y los popovers también están prohibidos en el renderizador de componentes front.
”Uso”
Estado no controlado
Root gestiona la visibilidad de forma predeterminada. Establece defaultOpen para su estado inicial. Los activadores, los controles de cierre, Escape y los clics fuera actualizan ese estado.
Anatomía
Ensamble
Portal, Backdrop, Viewport y Popup explícitamente. Cada parte del DOM acepta sus propios atributos nativos, controladores, className, style, ref y composición de render. Una ref apunta al elemento renderizado de esa parte. Popup no crea un portal, fondo ni viewport.
Estado controlado
Pasaopen y onOpenChange cuando la aplicación gestiona la visibilidad. El callback recibe el estado solicitado y los detalles del evento de Base UI, incluidos reason, event, trigger y cancel(). Actualiza el estado para aceptar un cambio o llama a eventDetails.cancel() para rechazarlo. onOpenChangeComplete se ejecuta cuando finaliza la animación de apertura o cierre.
Composición
Trigger y Close aceptan render para componerse con Button, como se muestra arriba. Los envoltorios personalizados deben reenviar las props y refs proporcionadas. Las partes del DOM conservan los nombres de clase, estilos y contratos de render con reconocimiento de estado de Base UI. Header, Body y Footer conservan su diseño con estilo y composición de div nativa.
Anida otro Dialog.Root dentro de un popup para abrir un segundo diálogo. Al cerrar el diálogo anidado, el foco vuelve a su activador en el diálogo principal.
Para abrir un diálogo desde triggers fuera de Root, cree un handle una vez con Dialog.createHandle\<TPayload>() y páselo a handle tanto en Root como en cada Trigger. Los valores de payload de Trigger están disponibles en la función de renderizado de Root. Dialog.Handle y el tipo público DialogHandle exponen el contrato del handle instalado:
Las acciones imperativas solo tienen efecto mientras el Root asociado está montado.
actionsRef de Root también expone close() y unmount() para un control explícito de la transición. Para controlar una animación de cierre externa, llame a eventDetails.preventUnmountOnClose() en onOpenChange y, luego, llame a la acción unmount() cuando finalice la animación.
Title usa Heading y de forma predeterminada es un h2 con texto grande, color de texto principal, alineación centrada y espaciado 4 debajo. Usa level para cambiar el nivel del encabezado independientemente de size, o color para cambiar su color de texto. Los elementos nativos className, style, refs y render se reenvían al encabezado. Mantén un elemento de encabezado al usar render. Description está centrada como Title; AlertDialog mantiene ambos alineados a la izquierda.
Popup no tiene relleno. Header, Body y Footer proporcionan la sangría, por lo que el contenido colocado directamente en Popup queda junto a sus bordes.
Foco, desplazamiento y cierre
Root.modal controla el límite de interacción:
Omita
Backdrop cuando no se necesite un fondo visible. Para un diálogo no modal cuyo viewport debe permitir que los eventos de puntero pasen a la página, use \<Dialog.Viewport data-backdrop-hidden="true">; Popup permanece interactivo. Omitir solo el fondo visual no cambia Root.modal.
Establece Popup.initialFocus o Popup.finalFocus en una ref o devolución de llamada para elegir los destinos del foco; false desactiva ese movimiento automático del foco. Los callbacks de foco reciben el tipo de interacción y conservan el comportamiento de retorno booleano, elemento, null y undefined de Base UI. Normalmente, al cerrar se restaura el foco al trigger o al elemento previamente enfocado.
Root.disablePointerDismissal evita que los clics fuera soliciten el cierre. Para evitar el cierre con Escape, cancela el cambio escape-key en onOpenChange. Proporciona siempre una forma visible de cerrar un diálogo modal.
Tamaños y portales
Popup.size acepta sm, compact, md, lg, xl y fullscreen, y su valor predeterminado es md. El contenido largo se desplaza dentro del popup. El ancho está limitado a la ventana gráfica.
Configure Portal.container para elegir un destino:
Portal.keepMounted conserva el contenido y el estado del formulario mientras está cerrado. Viewport y Popup trasladan la dirección de texto proporcionada a un contenedor externo; sus props explícitas dir tienen prioridad. Sin un proveedor de dirección ni dir explícito, heredan del destino. Consulte temas y DirectionProvider.
Personalice Backdrop y Viewport mediante sus propias props. Sus atributos nativos, controladores, refs y render se aplican a esos elementos independientemente de Popup. forceRender de Backdrop mantiene visible el fondo de un diálogo anidado cuando es necesario. El estado de apertura y transición de Base UI sigue estando disponible para estilos con reconocimiento de estado y callbacks de renderizado.
Migración
Envuelva el contenido existente deDialog.Popup en Dialog.Portal y Dialog.Viewport, y agregue un Dialog.Backdrop hermano dentro de Portal. Mueva container y keepMounted de Popup a Portal. Mueva las props anteriores de backdrop a Backdrop; sustituya backdrop={false} omitiendo Backdrop. Mueva viewportProps a Viewport, conservando data-backdrop-hidden="true" cuando el viewport deba permitir el paso de eventos de puntero externos. Mantenga size, initialFocus, finalFocus, los atributos nativos de popup y las refs de popup en Popup. Se eliminan las props de ensamblaje de Popup fusionadas.
Root, Trigger, Close, Title, Description, Header, Body, Footer y los handles existentes conservan sus funciones. Las props de partes públicas, los tipos de estado, acciones y detalles de eventos se exportan desde twenty-ui/primitives/surfaces.
”Props”
Dialog.Root
RefObject<DialogRootActions | null>
A ref to imperative actions.
unmount: Ends the closing phase of the dialog after an externally controlled closing animation finishes. CallpreventUnmountOnClose()inonOpenChangefirst, otherwise the dialog completes closing on its own. Whether it leaves the DOM is decided bykeepMountedon the portal.close: Closes the dialog imperatively when called.
ReactNode | PayloadChildRenderFunction<Payload>
Parts or a render function receiving the active trigger payload. Root renders no DOM node.
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.boolean
predeterminado:"false"
Whether to prevent the dialog from closing on outside presses.
For non-modal dialogs, this also prevents the dialog from closing when focus moves outside of it.
DialogHandle<Payload>
Connects detached triggers and imperative dialog actions.
boolean | "trap-focus"
predeterminado:"true"
Determines if the dialog enters a modal state when open.
true: user interaction is limited to just the dialog: focus is trapped, document page scroll is locked, and pointer interactions on outside elements are disabled.false: user interaction with the rest of the document is allowed.'trap-focus': focus is trapped inside the dialog, but document page scroll is not locked and pointer interactions outside of it remain enabled.
modal is true or 'trap-focus', render <Dialog.Close> inside <Dialog.Popup> so
touch screen readers can escape the popup.((open: boolean, eventDetails: DialogRootChangeEventDetails) => void)
Receives the requested state and Base UI event details, including reason, event, trigger and cancel().
((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).Dialog.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.
DialogHandle<Payload>
A handle to associate the trigger with a dialog.
Can be created with the Dialog.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.
((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null
Ref to the trigger button, or the element supplied through render.
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.
Dialog.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. Omit to use the nearest theme scope, then the parent portal or document body. Explicit null defers mounting; an element, ShadowRoot or ref keeps Base UI resolution.
boolean
predeterminado:"false"
Keeps the portal and its content mounted while closed.
Ref<HTMLDivElement>
Ref to the portal div, or the element supplied through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogPortalState>
Composes the portal element. Native props and handlers target it.
CSSProperties | ((state: DialogPortalState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Dialog.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"
Renders the backdrop even when this dialog is nested.
Ref<HTMLDivElement>
Ref to the backdrop div, or the element supplied through render.
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.
Dialog.Viewport
ReactNode
Popup and any other content within the positioning 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.
Ref<HTMLDivElement>
Ref to the viewport div, or the element supplied through render.
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.
Dialog.Popup
ReactNode
Dialog content. Compose inside Viewport and Portal; Popup does not create those parts or a Backdrop.
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)
Controls focus restoration on closing. Accepts a boolean, element ref or callback receiving the interaction type.
boolean | RefObject<HTMLElement | null> | ((openType: InteractionType) => boolean | void | HTMLElement | null)
Controls focus on opening. Accepts a boolean, element ref or callback receiving the interaction type.
Ref<HTMLDivElement>
Ref to the popup div, or the element supplied through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, DialogPopupState>
Composes the popup element while retaining native props, handlers, dialog semantics and focus behavior.
"compact" | "fullscreen" | "lg" | "md" | "sm" | "xl"
predeterminado:"md"
Width of the dialog, 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.
Dialog.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.
"primary" | "secondary" | "tertiary"
predeterminado:"primary"
Theme font color. Defaults to
primary.1 | 2 | 3 | 4 | 5 | 6
predeterminado:"2"
Semantic heading level, from
h1 through h6. Does not change the visual size. Defaults to 2.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."lg" | "md" | "sm" | "xl" | "xs" | "xxl"
predeterminado:"lg"
Visual font size, independent of the heading level. Defaults to
lg.CSSProperties | ((state: DialogTitleState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Dialog.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.
Ref<HTMLParagraphElement>
Ref to the description paragraph, or the element supplied through render.
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.
Dialog.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>).Ref<HTMLButtonElement>
Ref to the close button, or the element supplied through render.
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.
Dialog.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.Dialog.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.Dialog.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.