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?