Dynamic Badge Tooltips
Dynamic Truncating Badges with Tooltips in React
Introduction
Badges are a common UI element for displaying tags, categories, or statuses. But what happens when the text inside a badge is too long to fit nicely? A great user experience is to show a tooltip with the full text, but only when the text is actually truncated. In this post, we'll explore a React component that does exactly that: it detects when a badge's text is truncated and conditionally displays a tooltip.
The Problem: Truncated Text in Badges
When displaying tags or labels, it's common to limit their width to keep the UI clean. However, this can lead to text being cut off, especially for long tag names. Showing a tooltip with the full text is helpful but we only want to show it if the text is actually truncated.
The Solution: Measuring Truncation in React
The custom badge component solves this by:
- Rendering the tag name inside a span with the TailwindCSS truncate utility class.
- Using a React
ref
to access the DOM node of the span. - Comparing the
span
elements scrollWidth and clientWidth to determine if the text is truncated. - Conditionally wrapping the badge in a tooltip if truncation is detected.
Here's the relevant parts of the implementation:
How Does This Work?
- clientWidth is the visible width of the element, including padding but not the scrollbar, border, or margin.
- scrollWidth is the total width of the element's content, including the part not visible on the screen due to overflow.
- If
scrollWidth
is greater thanclientWidth
, it means some content is hidden (truncated).
Why This Matters
This approach provides a seamless user experience: tooltips only appear when they're needed, keeping the UI clean and accessible. It's a great example of combining React's DOM access with simple browser APIs to solve a common problem.
Try It Yourself
Below is a full implementation of my custom TagBadge
component. I have included the associated types and color picker component for convenience for a full solution:
Last updated on