I am using tailwind and shadcn for development.
My idea is that if the text in a column is larger than a certain number of pixels, it should be possible to see a tooltip from the shadcn library for the inscription in that cell, and if it is smaller, then without a tooltip.
I have a half-working solution, but it does not display ellipses if the text goes beyond the table cell (although the className is “truncate max-w-[250px]”)
And the main problem is that useEffect works after the component is rendered, so when I add the first long component, the tooltip is not visible for it until the next render, as soon as I add another element to the table, the tooltip becomes available for the previous one, but not for the new one
My code:
export default function App() {
const [users, setUsers] = useState([]);
const cellRef = useRef([]);
useEffect(() => {
cellRef.current.forEach(item => {
if (item) {
const textWidth = item.offsetWidth;
if (textWidth > 250) {
item.dataset.showtooltip = "true";
} else {
delete item.dataset.showtooltip;
}
}
})
}, [users])
function addUser(user) {
setUsers(prev => {
return [...prev, user]
});
}
return (
<div>
<DialogDemo onSave={addUser}/>
<Table>
<TableCaption>A list of your recent invoices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead className="w-[250px]">Name</TableHead>
<TableHead>Email</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.map((user, index) => (
<TableRow key={user.name}>
<TableCell className="truncate max-w-[250px] font-medium">
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<span ref={el => cellRef.current[index] = el}>{user.name}</span>
</TooltipTrigger>
{cellRef.current[index]?.dataset.showtooltip && (
<TooltipContent>
{user.name}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</TableCell>
<TableCell>{user.email}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)