UIPackage React Native
Search

Tooltip

Themed tooltip with press access, portal rendering, viewport bounds, and safe-area collision insets.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add tooltip

Source files

Expand a file to read the source the installer copies into your app.

components/ui/tooltip/Tooltip.tsx
import * as React from 'react'
import { Platform, ScrollView, StyleSheet, useWindowDimensions } from 'react-native'
import * as Primitive from '@rn-primitives/tooltip'
import { cssInterop } from 'react-native-css-interop'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { PortalWindow, usePopupDismiss } from '@/lib/portal'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'

cssInterop(Primitive.Root, { className: 'style' })
cssInterop(Primitive.Trigger, { className: 'style' })
cssInterop(Primitive.Content, { className: 'style' })
cssInterop(Primitive.Overlay, { className: 'style' })

export type TooltipProps = Primitive.RootProps & { className?: string }

// The headless tooltip does not export its context; its public trigger ref owns dismissal.
const TooltipContext = React.createContext<{
  open: boolean
  trigger: React.RefObject<Primitive.TriggerRef | null>
} | null>(null)

function useTooltipController() {
  const context = React.useContext(TooltipContext)
  if (!context) throw new Error('Tooltip components must be rendered inside Tooltip')
  return context
}

export const Tooltip = React.forwardRef<Primitive.RootRef, TooltipProps>(
  ({ className, onOpenChange, ...props }, ref) => {
    const [open, setOpen] = React.useState(false)
    const trigger = React.useRef<Primitive.TriggerRef>(null)
    return (
      <TooltipContext.Provider value={{ open, trigger }}>
        <Primitive.Root
          ref={ref}
          className={cn('self-start', className)}
          onOpenChange={(next) => {
            setOpen(next)
            onOpenChange?.(next)
          }}
          {...props}
        />
      </TooltipContext.Provider>
    )
  },
)
Tooltip.displayName = 'Tooltip'
export type TooltipTriggerProps = Omit<Primitive.TriggerProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const TooltipTrigger = React.forwardRef<Primitive.TriggerRef, TooltipTriggerProps>(
  ({ className, children, asChild, disabled, ...props }, ref) => {
    const { trigger } = useTooltipController()
    const setRef = React.useCallback(
      (node: Primitive.TriggerRef | null) => {
        trigger.current = node
        if (typeof ref === 'function') return ref(node)
        if (ref) ref.current = node
      },
      [ref, trigger],
    )
    return (
      <Primitive.Trigger
        {...props}
        ref={setRef}
        asChild={asChild}
        disabled={disabled}
        className={cn(
          'min-h-[48px] min-w-[48px] flex-row items-center justify-center gap-[8px] rounded-md border border-border bg-background px-[16px] py-[10px] active:bg-accent',
          disabled && 'opacity-50',
          className,
        )}
      >
        {asChild ? children : renderTextChildren(children)}
      </Primitive.Trigger>
    )
  },
)
TooltipTrigger.displayName = 'TooltipTrigger'
export type TooltipContentProps = Omit<Primitive.ContentProps, 'children'> & {
  children?: React.ReactNode
  className?: string
}
export const TooltipContent = React.forwardRef<Primitive.ContentRef, TooltipContentProps>(
  ({ className, children, asChild, insets, style, align = 'start', side = 'top', sideOffset = 8, ...props }, ref) => {
    const { open, trigger } = useTooltipController()
    const visible = open
    const popup = usePopupDismiss(visible, () => trigger.current?.close())
    const safe = useSafeAreaInsets()
    const { width, height } = useWindowDimensions()
    const bounds = { top: safe.top + 8, bottom: safe.bottom + 8, left: safe.left + 8, right: safe.right + 8, ...insets }
    const maxWidth = Math.max(0, Math.min(320, width - bounds.left - bounds.right))
    const maxHeight = Math.max(0, height - bounds.top - bounds.bottom)
    // Native headless content must unmount to release its platform Back subscription.
    if (Platform.OS !== 'web' && !visible) return null
    return (
      <Primitive.Portal
        forceMount={props.forceMount}
        hostName={popup.hostName}
        {...(Platform.OS === 'web'
          ? { container: (popup.container ?? undefined) as unknown as Primitive.PortalProps['container'] }
          : {})}
      >
        <PortalWindow layer={popup}>
          {Platform.OS !== 'web' ? <Primitive.Overlay accessible={false} style={StyleSheet.absoluteFill} /> : null}
          <Primitive.Content
            {...props}
            ref={ref}
            asChild={asChild}
            align={align}
            side={Platform.OS !== 'web' && (side === 'left' || side === 'right') ? 'top' : side}
            sideOffset={sideOffset}
            insets={bounds}
            className={cn('rounded-lg border border-border bg-popover p-[12px]', className)}
            style={StyleSheet.flatten([{ maxWidth, maxHeight }, style]) ?? undefined}
          >
            {asChild ? (
              children
            ) : (
              <ScrollView bounces={false} keyboardShouldPersistTaps="handled" style={{ maxHeight, flexGrow: 0 }}>
                {renderTextChildren(children)}
              </ScrollView>
            )}
          </Primitive.Content>
        </PortalWindow>
      </Primitive.Portal>
    )
  },
)
TooltipContent.displayName = 'TooltipContent'
components/ui/tooltip/index.ts
export * from './Tooltip'

Dependencies

Registry items

npm packages

  • @rn-primitives/tooltip
  • react-native-safe-area-context
  • react-native-css-interop
Browse overlays and feedback