Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React show Material-UI Tooltip only for text that has ellipsis

Looking for a way to have material-ui's tooltip expand the text in a table cell ONLY if the text is cut off with an ellipsis (overflowing).

Currently in my table I have a cell like this:

<TableCell className={classes.descriptionCell}>{row.description}</TableCell>

and my styling for descriptionCell is like this:

    descriptionCell: {
        whiteSpace: 'nowrap',
        maxWidth: '200px',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
    }

This makes the text behave the way I would like it to in this table, but I want to be able to hover and view the rest of it in a tooltip, preferably Material-UI's built in tooltip component.

I know there is a package that exists here https://www.npmjs.com/package/react-ellipsis-with-tooltip which should do this, BUT it uses bootstrap tooltip, not material UI.

like image 540
dave99collins Avatar asked Jun 13 '19 21:06

dave99collins


1 Answers

based on benjamin.keen answer, this is the functional version of his code:

import React, { useRef, useState, useEffect } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

const OverflowTip = ({ children }) => {
  const [isOverflowed, setIsOverflow] = useState(false);
  const textElementRef = useRef();
  useEffect(() => {
    setIsOverflow(textElementRef.current.scrollWidth > textElementRef.current.clientWidth);
  }, []);
  return (
    <Tooltip title={children} disableHoverListener={!isOverflowed}>
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {children}
      </div>
    </Tooltip>
  );
};
like image 148
iradkot Avatar answered Oct 04 '22 22:10

iradkot