Get the number of characters that are being shown on screen when `p` tag is truncated to two lines

Advertisements

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:

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

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?

>Solution :

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.

Leave a ReplyCancel reply