Skip to content

Instantly share code, notes, and snippets.

@samsol38
Created October 24, 2025 11:53
Show Gist options
  • Select an option

  • Save samsol38/b58fcf8a8e16d2eb220bb6491dc1ce1a to your computer and use it in GitHub Desktop.

Select an option

Save samsol38/b58fcf8a8e16d2eb220bb6491dc1ce1a to your computer and use it in GitHub Desktop.
calculate line
import React, { useEffect, useRef, useState } from "react";
import Typography from "@mui/material/Typography";
const TruncatedTypography = ({ text }: { text: string }) => {
const typographyRef = useRef<HTMLDivElement>(null);
const [firstLineText, setFirstLineText] = useState("");
useEffect(() => {
const getFirstLineText = () => {
const element = typographyRef.current;
if (!element) return;
const style = window.getComputedStyle(element);
const lineHeight = parseFloat(style.lineHeight);
// Create a range to measure the visible portion
const range = document.createRange();
range.setStart(element.firstChild as Node, 0);
range.setEnd(element.firstChild as Node, element.textContent?.length || 0);
const rects = range.getClientRects();
let visibleText = "";
for (const rect of rects) {
if (rect.height <= lineHeight) {
// Get visible text within the first line
const content = element.textContent || "";
visibleText = content.substring(0, range.endOffset);
break;
}
}
setFirstLineText(visibleText);
};
getFirstLineText();
window.addEventListener("resize", getFirstLineText); // Recalculate on resize
return () => window.removeEventListener("resize", getFirstLineText);
}, []);
return (
<div>
<Typography
ref={typographyRef}
noWrap
style={{
width: "300px", // Set a specific width to enable truncation
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{text}
</Typography>
<p>First Line Text: {firstLineText}</p>
</div>
);
};
export default TruncatedTypography;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment