Overflow Tooltip

A tooltip that only shows when text is too long.

Preview

The text in here is just a little too long

Installation

CLI

npx shadcn@latest add https://kelvinmai.io/r/overflow-tooltip.json

Manual

Install the following dependencies

npm install clsx tailwind-merge

Add a classname utility function

import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};

Copy and paste the following code into your project

components/overflow-tooltip.tsx
'use client';
import * as React from 'react';
import {
Tooltip,
TooltipProvider,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
export const OverflowTooltip: React.FC<
React.ComponentProps<typeof TooltipContent>
> = ({ className, children, ...props }) => {
const [overflowed, setOverflowed] = React.useState(false);
const ref = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
if (ref.current && ref.current?.scrollWidth > ref.current?.clientWidth) {
setOverflowed(true);
}
}, []);
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className='truncate' ref={ref}>
{children}
</div>
</TooltipTrigger>
{overflowed && (
<TooltipContent className={cn('text-sm', className)} {...props}>
{children}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
);
};

Update the import paths to match your project setup

Usage

import { OverflowTooltip } from '@/components/ui/overflow-tooltip';
export default function Demo() {
return (
<OverflowTooltip>
The text in here is just a little too long
</OverflowTooltip>
);
}

API Reference

Props

NameTypeRequiredDefaultDescription
alpha
boolean
No
undefined
A boolean to check whether or not to include color alpha picker.