2

I have a component in React that shows a text. If the text is too long, I'm truncating it into only two lines. I'm relying solely on CSS to do so. And there is another button that is being used to toggle the truncation. Here's the component:

const [showFull, toggleShowFull] = useReducer((s) => !s, false);

const TruncatableText = styled("p", {
  display: "-webkit-box",
  WebkitBoxOrient: "vertical",
  WebkitLineClamp: 2,
  lineHeight: 1.5,
  maxHeight: "3em",
  overflow: "hidden",
  textOverflow: "ellipsis",
  cursor: "pointer",
  width: "100%",

  variants: {
    showFull: {
      true: {
        WebkitLineClamp: 1000,
        maxHeight: "100%",
      },
    },
  },
});

return (
  <>
    <TruncatableText showFull={showFull}>
      {text}
    </TruncatableText>

    <Button onClick={toggleShowFull}>
      {showFull ? "Hide Full Text" : "Show Full Text"}
    </Button>
  </>
)

Here's a preview of when the text is truncated:

Truncated Version

And here's a preview of when the text is expanded:

Expanded Version

Now I want to show the button if and only if the text is being truncated.

I thought of an idea that I can somehow get the number of characters that are being shown on the p tag. I tried getting the inner text of the p tag, but it gives me the whole text even if it's truncated. Can anyone please help me with how can I get the number of characters that are visible on the p tag?

Or is there any other way to do what I'm trying to do?

Shakirul Hasan
  • 678
  • 1
  • 5
  • 14
  • Related https://stackoverflow.com/questions/7738117/html-text-overflow-ellipsis-detection – James Apr 07 '23 at 17:16
  • Thank you, but my problem is a bit different. In that question, the text was truncated to a certain width in a single line. As a result, comparing `scrollWidth` and `offsetWidth` was enough to solve that. In my case, the width is same always, as I'm truncating text to two lines. I tried doing the same with height, but it didn't help. As the extra hight is just being hidden because of overflow. – Shakirul Hasan Apr 07 '23 at 17:38

1 Answers1

1

The innerHTML is unchanged when the text is truncated

It will always be the full text, because the truncation happens at the CSS level (i.e. when it is being displayed).

You should approach it by measuring the height of the TruncatableText component

Find out what that is for truncated text, and then if it is longer than that, you know you are expanded.

Of course, this will not on its own help you know whether the text is merely so short that the height is within the limit. That is more complex a question to answer.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • 1
    Thanks for your answer. Got an idea from it. I can give a fixed `line-height`, in pixels. And check if the height of the component is larger than twice that fixed `line-height`. – Shakirul Hasan Apr 07 '23 at 17:42