Обзор
ИспользуйтеTooltip для краткого пояснения элемента управления или усечённого текста. Необходимая информация должна быть видимой, элементы управления должны иметь доступное имя; используйте Popover, если содержимое включает ссылки, кнопки или другие элементы управления.
Использование
children. Нативные элементы получают атрибуты триггера, обработчики событий и ref напрямую. Пользовательские компоненты-триггеры должны перенаправлять их все. Элемент-обёртка также работает с компонентом, который не перенаправляет все свойства триггера.
При наведении всплывающая подсказка открывается через delay миллисекунд; по умолчанию используется 600. При фокусе с клавиатуры она открывается немедленно. По умолчанию closeDelay равен 0; наведение на всплывающее окно сохраняет его открытым, если не задан disableHoverablePopup. Escape закрывает её.
Управляемое состояние
Используйтеopen и onOpenChange вместе, когда приложению принадлежит управление видимостью. Используйте defaultOpen только для задания начальной видимости неуправляемой всплывающей подсказки.
Расширенное содержимое и композиция
Сокращённый вариант принимаетdescription и startIcon наряду с content. Пользовательское содержимое в виде узла отображается как задано, если описание или значок не запрашивают макет заголовка.
Tooltip.Body. Явно соберите портал, позиционирование, всплывающее окно и необязательную стрелку. Popup отображает свои дочерние элементы в переданном виде; Body предоставляет тот же макет с заголовком, описанием и декоративной иконкой, что и сокращённый вариант.
Tooltip.Body принимает необязательные дочерние элементы заголовка, а также узлы description и startIcon. Для заголовков используется средняя насыщенность; для описаний — дополнительный цвет tooltip; переносы строк сохраняются, а длинный текст переносится. Для tooltip только с описанием не добавляйте дочерние элементы заголовка. Значок является декоративным и отображается только при наличии заголовка. Body не добавляет роль tooltip, стилизацию popup, изменение размера или позиционирование. Поддерживается произвольное содержимое Popup. При типизации обёртки импортируйте TooltipBodyProps из twenty-ui/primitives/surfaces.
Каждая DOM-часть принимает нативные свойства, ref и композицию render с элементом или обратным вызовом. Нативные свойства верхнего уровня сокращённого варианта, render и ref нацелены на Popup. Используйте triggerProps, positionerProps и portalProps для настройки других целей; они переопределяют значения по умолчанию сокращённого варианта. Дочерние элементы предоставляют элемент отображения триггера по умолчанию. Обе формы сохраняют управляемое/неуправляемое состояние Root и сведения о событиях обратных вызовов Base UI, включая отмену, причину, исходное событие и активный триггер.
Tooltip.createHandle\<TPayload>() подключает отсоединённые триггеры к любой из форм через handle. Дочерние элементы составного Root или content сокращённого варианта могут быть функцией, получающей типизированную активную полезную нагрузку. Tooltip.Handle и публичный тип TooltipHandle предоставляют контракт установленного дескриптора. Дескрипторы поддерживают императивные open(triggerId) и close(), пока их Root смонтирован.
Миграция
Заменитеcontent={<Tooltip.Content description={description} startIcon={icon}>title</Tooltip.Content>} на content={title} description={description} startIcon={icon}. При составном использовании применяйте Tooltip.Body для общего макета заголовка и описания либо создайте собственное содержимое. Tooltip.Content и TooltipContentProps удалены.
Существующие свойства позиционирования составного Popup переносятся в Positioner. Оберните его в Portal, перенесите container и keepMounted в Portal, оставьте maxWidth в Popup и замените arrow дочерним элементом Arrow. При необходимости явно сохраните прежние интервалы с помощью sideOffset={10}. Составной Positioner сохраняет значение Base UI sideOffset={0}. Обе формы по умолчанию ограничивают Popup до 300 пикселей.
Отключённые элементы управления
Нативные отключённые кнопки не могут получать фокус с клавиатуры. Оберните такую кнопку в фокусируемый триггер, чтобы пользователи могли узнать, почему действие недоступно.disabled для сокращённого варианта или Root отключает саму всплывающую подсказку. disabled триггера отключает взаимодействие со всплывающей подсказкой этого триггера. Отключайте нативный элемент управления через его собственные свойства или элемент отображения Trigger.
Размещение и переполняющий текст
Для сокращённой формы по умолчанию используютсяside="top", align="center" и sideOffset={10}. Как сокращённые, так и составные всплывающие подсказки имеют максимальную ширину 300 пикселей, ограниченную доступным пространством рядом с якорем. Передайте maxWidth в сокращённую подсказку или Tooltip.Popup, чтобы выбрать другое максимальное значение, включая более широкие предварительные просмотры. Встроенные стили всплывающих окон остаются доступными для настройки пользовательского размера. Размещение корректируется в соответствии с доступным пространством. Открытая всплывающая подсказка скрывается, когда её якорь прокручивается за пределы видимости, в том числе за пределы контейнера прокрутки. Используйте arrow для стрелки и container, чтобы переопределить назначение портала темы; см. темизацию.
Используйте OverflowingTextWithTooltip, когда текстовая метка должна показывать полное значение только при усечении. Его существующие свойства text, tooltipContent и tooltipPlace остаются доступными.
Свойства
Справочник генерируется из публичных типов компонентов. Также принимаются нативные атрибуты всплывающего окна и обработчики событий.RefObject<TooltipRootActions | null>
A ref to imperative actions.
unmount: Ends the closing phase of the tooltip after an externally controlled closing animation finishes. CallpreventUnmountOnClose()inonOpenChangefirst, otherwise the tooltip completes closing on its own. Whether it leaves the DOM is decided bykeepMountedon the portal.close: Closes the tooltip imperatively when called.
"center" | "end" | "start"
по умолчанию:"center"
Alignment relative to the trigger. Defaults to center.
number | OffsetFunction
по умолчанию:"0"
Offset along the alignment axis in pixels.
Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null
An explicit positioning anchor for the popup.
boolean
Displays an arrow pointing to the trigger. Defaults to false.
number
по умолчанию:"5"
Minimum distance from the arrow to the popup edges.
ReactElement<unknown, string | JSXElementConstructor<any>>
обязательно
A single trigger element. Custom components must forward their ref, native attributes, and event handlers.
string | ((state: TooltipPopupState) => string | undefined)
Additional CSS class for the popup.
number
по умолчанию:"0"
Delay in milliseconds before closing after hover ends. Defaults to 0.
boolean
по умолчанию:"true"
Whether the tooltip should close when this trigger is clicked.
CollisionAvoidance
Determines how to handle collisions when positioning the popup.
side controls overflow on the preferred placement axis (top/bottom or left/right):'flip': keep the requested side when it fits; otherwise try the opposite side (topandbottom, orleftandright).'shift': never change side; keep the requested side and move the popup within the clipping boundary so it stays visible.'none': do not correct side-axis overflow.
align controls overflow on the alignment axis (start/center/end):'flip': keep side, but swapstartandendwhen the requested alignment overflows.'shift': keep side and requested alignment, then nudge the popup along the alignment axis to fit.'none': do not correct alignment-axis overflow.
fallbackAxisSide controls fallback behavior on the perpendicular axis when the
preferred axis cannot fit:'start': allow perpendicular fallback and try the logical start side first (topbeforebottom, orleftbeforerightin LTR).'end': allow perpendicular fallback and try the logical end side first (bottombeforetop, orrightbeforeleftin LTR).'none': do not fallback to the perpendicular axis.
side is 'shift', explicitly setting align only supports 'shift' or 'none'.
If align is omitted, it defaults to 'flip'.Boundary
по умолчанию:"clipping-ancestors"
An element or a rectangle that delimits the area that the popup is confined to.
Padding
по умолчанию:"5"
Additional space to maintain from the edge of the collision boundary.
HTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot | null> | null
Portal destination. Defaults to the current theme container.
ReactNode | PayloadChildRenderFunction<TPayload>
обязательно
Supplementary content, or a function receiving the active trigger payload. Strings and numbers use the shorthand title layout.
boolean
по умолчанию:"false"
Initial visibility when the tooltip manages its own state.
string | null
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
defaultOpen prop to create an initially open tooltip.number
по умолчанию:"600"
Delay in milliseconds before opening on hover. Defaults to 600.
ReactNode
Optional secondary text below the shorthand title.
boolean
по умолчанию:"false"
Whether to disable the popup from tracking any layout shift of its positioning anchor.
boolean
по умолчанию:"false"
Prevents the tooltip from opening.
boolean
по умолчанию:"false"
Prevents hovering over the popup from keeping it open.
TooltipHandle<TPayload>
Connects detached triggers and preserves their typed payloads.
boolean
Keeps the popup mounted while closed.
MaxWidth<string | number>
Maximum popup width. Defaults to 300 pixels and is capped by the space available beside the anchor.
((open: boolean, eventDetails: TooltipRootChangeEventDetails) => void)
Receives the requested open state and unchanged Base UI event details, including reason, event, trigger and cancel().
((open: boolean) => void)
Event handler called after any animations complete when the tooltip is opened or closed.
boolean
Controlled visibility of the tooltip.
TooltipPortalProps
Full Portal props, including native props, ref and render. Overrides shorthand portal defaults.
TooltipPositionerProps
Full Positioner props, including native props, ref and render. Overrides shorthand placement defaults.
"absolute" | "fixed"
по умолчанию:"absolute"
CSS positioning method for the popup.
Ref<HTMLDivElement>
Ref forwarded to the popup element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPopupState>
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."bottom" | "inline-end" | "inline-start" | "left" | "right" | "top"
по умолчанию:"top"
Preferred side of the trigger. Defaults to top and may change to avoid collisions.
number | OffsetFunction
по умолчанию:"10"
Distance from the trigger in pixels. Defaults to 10.
ReactNode
Optional node before the shorthand title.
boolean
по умолчанию:"false"
Whether to maintain the popup in the viewport after
the anchor element was scrolled out of view.
CSSProperties | ((state: TooltipPopupState) => CSSProperties | undefined)
Inline styles for the popup.
"both" | "none" | "x" | "y"
по умолчанию:"none"
Determines which axis the tooltip should track the cursor on.
string | null
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
open prop to create a controlled tooltip.
There’s no need to specify this prop when the tooltip is uncontrolled (that is, when the open prop is not set).TooltipTriggerProps<TPayload>
Full Trigger props, including native props, ref, render and payload. Overrides the shorthand trigger defaults.
boolean
Fades and slides the popup out when it closes instead of hiding it at once.
Tooltip.Root
RefObject<TooltipRootActions | null>
A ref to imperative actions.
unmount: Ends the closing phase of the tooltip after an externally controlled closing animation finishes. CallpreventUnmountOnClose()inonOpenChangefirst, otherwise the tooltip completes closing on its own. Whether it leaves the DOM is decided bykeepMountedon the portal.close: Closes the tooltip imperatively when called.
ReactNode | PayloadChildRenderFunction<Payload>
Parts or a render function receiving the active trigger payload. Root renders no DOM node.
boolean
по умолчанию:"false"
Whether the tooltip is initially open.To render a controlled tooltip, use the
open prop instead.string | null
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
defaultOpen prop to create an initially open tooltip.boolean
по умолчанию:"false"
Whether the tooltip is disabled.
boolean
по умолчанию:"false"
Whether the tooltip contents can be hovered without closing the tooltip.
TooltipHandle<Payload>
Connects detached triggers and imperative open/close actions.
((open: boolean, eventDetails: TooltipRootChangeEventDetails) => void)
Receives the requested open state and unchanged Base UI event details, including reason, event, trigger and cancel().
((open: boolean) => void)
Event handler called after any animations complete when the tooltip is opened or closed.
boolean
Whether the tooltip is currently open.
"both" | "none" | "x" | "y"
по умолчанию:"none"
Determines which axis the tooltip should track the cursor on.
string | null
ID of the trigger that the tooltip is associated with.
This is useful in conjunction with the
open prop to create a controlled tooltip.
There’s no need to specify this prop when the tooltip is uncontrolled (that is, when the open prop is not set).Tooltip.Trigger
string | ((state: TooltipTriggerState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
number
по умолчанию:"0"
How long to wait before closing the tooltip. Specified in milliseconds.
boolean
по умолчанию:"true"
Whether the tooltip should close when this trigger is clicked.
number
по умолчанию:"600"
How long to wait before opening the tooltip on hover. Specified in milliseconds.
boolean
по умолчанию:"false"
Disables tooltip interaction for this trigger without disabling its native element.
TooltipHandle<Payload>
A handle to associate the trigger with a tooltip.
Payload
A payload to pass to the tooltip when it is opened.
((((instance: HTMLButtonElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<HTMLButtonElement | null>) & (((instance: HTMLElement | null) => void | (() => VoidOrUndefinedOnly)) | RefObject<...>)) | null
Ref to the rendered trigger element, a button by default.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipTriggerState>
Composes a native element or a component that forwards attributes, handlers and ref.
CSSProperties | ((state: TooltipTriggerState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Portal
string | ((state: TooltipPortalState) => 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. Defaults to the current theme container, then the document body.
boolean
по умолчанию:"false"
Whether to keep the portal mounted in the DOM while the popup is hidden.
Ref<HTMLDivElement>
Ref to the portal div.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPortalState>
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: TooltipPortalState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Positioner
"center" | "end" | "start"
по умолчанию:"center"
How to align the popup relative to the specified side.
number | OffsetFunction
по умолчанию:"0"
Additional offset along the alignment axis in pixels.
Also accepts a function that returns the offset to read the dimensions of the anchor
and positioner elements, along with its side and alignment.The function takes a
data object parameter with the following properties:data.anchor: the dimensions of the anchor element with propertieswidthandheight.data.positioner: the dimensions of the positioner element with propertieswidthandheight.data.side: which side of the anchor element the positioner is aligned against.data.align: how the positioner is aligned relative to the specified side.
Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null
An element to position the popup against.
By default, the popup will be positioned against the trigger.
number
по умолчанию:"5"
Minimum distance to maintain between the arrow and the edges of the popup.Use it to prevent the arrow element from hanging out of the rounded corners of a popup.
string | ((state: TooltipPositionerState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
CollisionAvoidance
Determines how to handle collisions when positioning the popup.
side controls overflow on the preferred placement axis (top/bottom or left/right):'flip': keep the requested side when it fits; otherwise try the opposite side (topandbottom, orleftandright).'shift': never change side; keep the requested side and move the popup within the clipping boundary so it stays visible.'none': do not correct side-axis overflow.
align controls overflow on the alignment axis (start/center/end):'flip': keep side, but swapstartandendwhen the requested alignment overflows.'shift': keep side and requested alignment, then nudge the popup along the alignment axis to fit.'none': do not correct alignment-axis overflow.
fallbackAxisSide controls fallback behavior on the perpendicular axis when the
preferred axis cannot fit:'start': allow perpendicular fallback and try the logical start side first (topbeforebottom, orleftbeforerightin LTR).'end': allow perpendicular fallback and try the logical end side first (bottombeforetop, orrightbeforeleftin LTR).'none': do not fallback to the perpendicular axis.
side is 'shift', explicitly setting align only supports 'shift' or 'none'.
If align is omitted, it defaults to 'flip'.Boundary
по умолчанию:"clipping-ancestors"
An element or a rectangle that delimits the area that the popup is confined to.
Padding
по умолчанию:"5"
Additional space to maintain from the edge of the collision boundary.
boolean
по умолчанию:"false"
Whether to disable the popup from tracking any layout shift of its positioning anchor.
"absolute" | "fixed"
по умолчанию:"absolute"
Determines which CSS
position property to use.Ref<HTMLDivElement>
Ref to the positioning div. Native props, styles and render target this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPositionerState>
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."bottom" | "inline-end" | "inline-start" | "left" | "right" | "top"
по умолчанию:"top"
Preferred physical or logical side of the anchor. Defaults to top.
number | OffsetFunction
по умолчанию:"0"
Distance from the anchor. Defaults to 0 in compound usage. Accepts a number or positioning function.
boolean
по умолчанию:"false"
Whether to maintain the popup in the viewport after
the anchor element was scrolled out of view.
CSSProperties | ((state: TooltipPositionerState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Popup
ReactNode
Content rendered as supplied. Does not create a portal, positioner, title layout or arrow.
string | ((state: TooltipPopupState) => string | undefined)
CSS class applied to the element, or a function that
returns a class based on the component’s state.
MaxWidth<string | number>
Maximum popup width. Defaults to 300 pixels and is capped by the space available beside the anchor.
Ref<HTMLDivElement>
Ref to the popup div. Native props, styles and render target this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipPopupState>
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: TooltipPopupState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
boolean
по умолчанию:"false"
Enables the optional Twenty exit transition.
Tooltip.Body
ReactNode
Optional title content, displayed with medium weight. Omit it for a description-only tooltip.
ReactNode
Optional secondary content. Preserves line breaks and wraps long text.
Ref<HTMLDivElement>
Ref to the body div. Native props, styles and render target this element.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>
Composes the body root through an element or render callback while preserving its layout and content.
ReactNode
Optional decorative node before the title. Omitted when the title is empty.
Tooltip.Arrow
string | ((state: TooltipArrowState) => 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 arrow div. Compose inside Popup.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipArrowState>
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: TooltipArrowState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Viewport
ReactNode
The content to render inside the transition container.
string | ((state: TooltipViewportState) => 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 content-transition div. Useful when several triggers share changing content.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, TooltipViewportState>
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: TooltipViewportState) => CSSProperties | undefined)
Style applied to the element, or a function that
returns a style object based on the component’s state.
Tooltip.Provider
ReactNode
Tooltips sharing delay, closeDelay and timeout configuration. Provider renders no DOM node.
number
How long to wait before closing a tooltip. Specified in milliseconds.
number
How long to wait before opening the tooltip on hover. Specified in milliseconds.
number
по умолчанию:"400"
Another tooltip will open instantly if the previous tooltip
is closed within this timeout. Specified in milliseconds.