Skip to content

Tooltip

A lightweight popup that provides helpful information on hover or focus. Built on Radix UI with customizable positions, sizes, and animations.

Installation

Add Tooltip to your project with the CK-UI CLI. It copies the source into your project, so the code is yours to change.

Terminal
npx ck-ui-cli@latest add tooltip
Adds
Tooltip.tsxThemeScope.tsxto your CK-UI folder (src/components/ck-ui by default)
Installs
@radix-ui/react-slot@radix-ui/react-tooltipif your project does not have them yet

First time with CK-UI in this project? Run npx ck-ui-cli@latest init once before adding components. The installation guide explains what it sets up.

Manual installationInstall the packages and copy the files yourself.

Install the following dependencies

Run these commands in your terminal to install the required packages

Terminal
npm install @radix-ui/react-tooltip @radix-ui/react-slot

Add the ThemeScope component

Tooltip imports ./ThemeScope, so add this file next to it

/components/ui/ThemeScope.tsx
"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

/*
 * A local light/dark boundary. Everything inside renders in `theme`, whatever the site theme is: the semantic tokens
 * (`bg-background`, `text-foreground`, …) and every `dark:` utility resolve to the nearest boundary, not to <html>.
 * Overlays that portal out of the tree (Select, Popover, Tooltip, Dropdown, Modal, AlertDialog, Drawer, Toast) render
 * into a layer that carries the same theme, so a menu opened inside a dark scope is dark too.
 *
 * It never touches <html>, the site's theme state or its storage. Without `theme` it renders no theme class and
 * follows the surrounding theme. Nest at most one scope below the site theme (see `darkMode` in tailwind.config.ts).
 */

export type ScopeTheme = "light" | "dark";

const PortalContainerContext = React.createContext<HTMLElement | null>(null);

/** Where overlays portal to: the nearest themed ThemeScope's layer, or null for the default (document.body). */
export function usePortalContainer() {
    return React.useContext(PortalContainerContext);
}

// A themed layer at the end of <body> for portalled overlays. Only created while the scope sets a theme, so a scope
// that follows the site leaves the document exactly as it was.
function usePortalLayer(theme: ScopeTheme | undefined) {
    const [layer, setLayer] = React.useState<HTMLElement | null>(null);
    const themed = theme !== undefined;

    React.useEffect(() => {
        if (!themed) return;
        const element = document.createElement("div");
        element.setAttribute("data-theme-scope-layer", "");
        document.body.appendChild(element);
        setLayer(element);
        return () => {
            element.remove();
            setLayer(null);
        };
    }, [themed]);

    React.useEffect(() => {
        if (!layer || !theme) return;
        // text-foreground: portalled text that sets no colour of its own resolves against the layer's tokens.
        layer.className = `${theme} text-foreground`;
    }, [layer, theme]);

    return layer;
}

export interface RootProps extends React.HTMLAttributes<HTMLDivElement> {
    /** Theme for this subtree. Leave undefined to follow the surrounding (site) theme. */
    theme?: ScopeTheme;
}

const Root = React.forwardRef<HTMLDivElement, RootProps>(({ theme, className, children, ...props }, ref) => {
    const layer = usePortalLayer(theme);
    // A scope that follows its surroundings keeps the surrounding scope's layer.
    const outerLayer = usePortalContainer();

    return (
        <div ref={ref} data-theme-scope={theme} className={cn(theme && [theme, "text-foreground"], className)} {...props}>
            <PortalContainerContext.Provider value={theme ? layer : outerLayer}>{children}</PortalContainerContext.Provider>
        </div>
    );
});
Root.displayName = "ThemeScope.Root";

export { Root };

Create or update your Tooltip component

Copy this code to create your Tooltip component

/components/ui/Tooltip.tsx
"use client";

import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { Slottable } from "@radix-ui/react-slot";
import { cn } from "@/lib/utils";
import { usePortalContainer } from "./ThemeScope";

const DEFAULT_DELAY_DURATION = 200;
const DEFAULT_SKIP_DELAY_DURATION = 300;

// Tracks whether a Tooltip.Provider is above, so standalone Roots can create their own.
const TooltipProviderContext = React.createContext(false);

export type ProviderProps = TooltipPrimitive.TooltipProviderProps;

/**
 * Shares delay settings between tooltips. Wrap a region (or the app) once so moving between tooltips skips the
 * open delay (`skipDelayDuration`). Defaults match standalone tooltips: `delayDuration` 200ms, `skipDelayDuration` 300ms.
 */
const Provider = ({ children, delayDuration = DEFAULT_DELAY_DURATION, skipDelayDuration = DEFAULT_SKIP_DELAY_DURATION, ...props }: ProviderProps) => {
    return (
        <TooltipProviderContext.Provider value={true}>
            <TooltipPrimitive.Provider delayDuration={delayDuration} skipDelayDuration={skipDelayDuration} {...props}>
                {children}
            </TooltipPrimitive.Provider>
        </TooltipProviderContext.Provider>
    );
};
Provider.displayName = "Tooltip.Provider";

export interface RootProps extends React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Root> {
    /** Open delay in ms. Inside a `Tooltip.Provider` it defaults to the Provider's value; otherwise 200. */
    delayDuration?: number;
    /**
     * Skip-delay window in ms for a Root used without `Tooltip.Provider` (reopening within it is instant). @default 300
     * Inside a Provider this prop is ignored; set it on the Provider instead.
     */
    skipDelayDuration?: number;
}

/** Works inside a shared `Tooltip.Provider` or standalone (it then creates its own Provider). */
const Root = ({ children, delayDuration, skipDelayDuration, ...props }: RootProps) => {
    const hasProvider = React.useContext(TooltipProviderContext);

    if (hasProvider) {
        return (
            <TooltipPrimitive.Root delayDuration={delayDuration} {...props}>
                {children}
            </TooltipPrimitive.Root>
        );
    }

    return (
        <Provider delayDuration={delayDuration ?? DEFAULT_DELAY_DURATION} skipDelayDuration={skipDelayDuration ?? DEFAULT_SKIP_DELAY_DURATION}>
            <TooltipPrimitive.Root {...props}>{children}</TooltipPrimitive.Root>
        </Provider>
    );
};
Root.displayName = "Tooltip.Root";

/** The element the tooltip describes. It must be focusable (use `asChild` with a button or link) so keyboard users get the tooltip too. */
const Trigger = React.forwardRef<React.ElementRef<typeof TooltipPrimitive.Trigger>, React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Trigger>>((props, ref) => (
    <TooltipPrimitive.Trigger ref={ref} {...props} />
));
Trigger.displayName = "Tooltip.Trigger";

// ---------------------------------------------------------------------------------------------
// Content
// ---------------------------------------------------------------------------------------------

export type TooltipSize = "sm" | "md" | "lg";
/** @deprecated Use `sm` / `md` / `lg`. */
type LegacyTooltipSize = "small" | "medium" | "large";

const LEGACY_SIZES: Record<LegacyTooltipSize, TooltipSize> = { small: "sm", medium: "md", large: "lg" };

export function resolveTooltipSize(size?: TooltipSize | LegacyTooltipSize | null): TooltipSize {
    if (!size) return "md";
    return size in LEGACY_SIZES ? LEGACY_SIZES[size as LegacyTooltipSize] : (size as TooltipSize);
}

const sizeClasses: Record<TooltipSize, string> = {
    sm: "px-2 py-1 size-p-xs rounded-md",
    md: "px-3 py-1.5 size-p-sm rounded-md",
    lg: "px-4 py-3 size-p-sm rounded-xl",
};

type TooltipPosition = "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right" | "left" | "right";
type Side = "top" | "right" | "bottom" | "left";
type Align = "start" | "center" | "end";

const PLACEMENT_BY_POSITION: Record<TooltipPosition, { side: Side; align: Align }> = {
    "top-left": { side: "top", align: "start" },
    "top-center": { side: "top", align: "center" },
    "top-right": { side: "top", align: "end" },
    "bottom-left": { side: "bottom", align: "start" },
    "bottom-center": { side: "bottom", align: "center" },
    "bottom-right": { side: "bottom", align: "end" },
    left: { side: "left", align: "center" },
    right: { side: "right", align: "center" },
};

// Enter animation runs on mount for both "delayed-open" and "instant-open"; exit runs on "closed".
const BASE_ANIMATION = "animate-in fade-in-0 duration-fast data-[state=closed]:animate-out data-[state=closed]:fade-out-0";

const ANIMATION_CLASSES: Record<"fade" | "scale" | "slide", string> = {
    fade: BASE_ANIMATION,
    scale: [BASE_ANIMATION, "zoom-in-95 data-[state=closed]:zoom-out-95"].join(" "),
    slide: [
        BASE_ANIMATION,
        "data-[side=bottom]:slide-in-from-top-2 data-[side=bottom]:data-[state=closed]:slide-out-to-top-2",
        "data-[side=left]:slide-in-from-right-2 data-[side=left]:data-[state=closed]:slide-out-to-right-2",
        "data-[side=right]:slide-in-from-left-2 data-[side=right]:data-[state=closed]:slide-out-to-left-2",
        "data-[side=top]:slide-in-from-bottom-2 data-[side=top]:data-[state=closed]:slide-out-to-bottom-2",
    ].join(" "),
};

export interface ContentProps extends React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> {
    showArrow?: boolean;
    /** Removes the default surface, padding and typography. */
    unstyled?: boolean;
    animation?: "fade" | "scale" | "slide";
    /** Padding and text size. `small` / `medium` / `large` are deprecated aliases. @default "md" */
    size?: TooltipSize | LegacyTooltipSize;
    /** Placement shorthand. Explicit `side` / `align` props take precedence. @default "top-center" */
    position?: TooltipPosition;
}

/** The tooltip bubble; `className` goes on it. Radix links it to the trigger with `role="tooltip"` + `aria-describedby`. */
const Content = React.forwardRef<React.ElementRef<typeof TooltipPrimitive.Content>, ContentProps>(
    (
        {
            children,
            className,
            side: sideProp,
            align: alignProp,
            sideOffset = 6,
            collisionPadding = 12,
            arrowPadding = 12,
            showArrow = true,
            unstyled,
            animation = "slide",
            size,
            position = "top-center",
            ...props
        },
        forwardedRef
    ) => {
        const placement = PLACEMENT_BY_POSITION[position];
        const container = usePortalContainer();

        return (
            <TooltipPrimitive.Portal container={container}>
                <TooltipPrimitive.Content
                    ref={forwardedRef}
                    side={sideProp ?? placement.side}
                    align={alignProp ?? placement.align}
                    sideOffset={sideOffset}
                    collisionPadding={collisionPadding}
                    arrowPadding={arrowPadding}
                    className={cn(
                        "z-tooltip",
                        !unstyled && ["w-max max-w-xs bg-background text-foreground shadow-medium ring-1 ring-border", sizeClasses[resolveTooltipSize(size)]],
                        ANIMATION_CLASSES[animation],
                        className
                    )}
                    {...props}
                >
                    <Slottable>{children}</Slottable>

                    {showArrow && (
                        <TooltipPrimitive.Arrow asChild>
                            <div className="block size-[11px] -translate-y-[calc(50%)] -rotate-45 rounded-bl-[3px] border border-border bg-background [clip-path:polygon(0_100%,0_0,100%_100%)]"></div>
                        </TooltipPrimitive.Arrow>
                    )}
                </TooltipPrimitive.Content>
            </TooltipPrimitive.Portal>
        );
    }
);
Content.displayName = "Tooltip.Content";

export { Provider, Root, Trigger, Content };

Test Your Component

  • 1. Add the component to a test page
  • 2. Check all props and variants work as expected
  • 3. Verify responsive behavior
  • 4. Test with different content/data
  • 5. Ensure accessibility features work correctly

Positions

Tooltips can be positioned in different directions around the trigger element.

Sizes

Tooltips come in different sizes to accommodate various content needs.

Animations

Various animations can be applied to tooltips when they appear and disappear.

API Reference

The Tooltip component is built on top of the Radix UI Tooltip primitive and extends its functionality with additional styling options and features.

Tooltip.Provider

Provider component that shares tooltip settings across all tooltips in its scope. Wrap a group of tooltips (or the whole app) in one Provider so moving between them skips the open delay. A Tooltip.Root outside any Provider creates its own.

See Radix UI docs for base props.

PropTypeDefaultDescription
delayDuration"number""200"

Default delay duration for all tooltips (ms)

skipDelayDuration"number""300"

Skip delay when quickly moving between tooltips (ms)

disableHoverableContent"boolean""false"

Prevents hovering content from keeping tooltip open

Tooltip.Root

The main container component that manages the tooltip state.

See Radix UI docs for base props. Only extended props shown below.

PropTypeDefaultDescription
delayDuration"number""200"

Delay in ms before showing the tooltip. Inside a Tooltip.Provider it defaults to the Provider's value.

skipDelayDuration"number""300"

Only for a Root used without Tooltip.Provider (it then creates its own). Inside a Provider, set it on the Provider instead.

Tooltip.Trigger

The element that triggers the tooltip to appear when hovered or focused. It must be focusable (use asChild with a button or link) so keyboard users get the tooltip too.

See Radix UI docs for base props.

PropTypeDefaultDescription
asChild"boolean""false"

Merges props onto child element

Tooltip.Content

The content displayed when the tooltip is visible.

See Radix UI docs for base props. Only extended props shown below.

PropTypeDefaultDescription
showArrow"boolean""true"

Whether to show the arrow indicator

unstyled"boolean""false"

Removes the default surface, padding and typography

animation
"fade""scale""slide"
"slide"

Animation style when opening/closing

size
"sm""md""lg"
"md"

Size variant of the tooltip. small / medium / large are deprecated aliases.

position
"top-left""top-center""top-right""bottom-left""bottom-center""bottom-right""left""right"
"top-center"

Position relative to the trigger

Used in these blocks

Block families with at least one block built on this component. Each page previews its blocks and lists the components and packages they use.