useIsTextTruncated
Example
import useIsTextTruncated from "@/hooks/useIsTextTruncated";
import { useRef } from "react";
export default function UseIsTextTruncated() {
const refOfValue = useRef(null);
const refOfValue2 = useRef(null);
const itsTruncatedValue = useIsTextTruncated(refOfValue);
const notTruncatedValue = useIsTextTruncated(refOfValue2);
return (
<div className="flex flex-col items-center justify-center gap-4 p-4">
<div className="flex flex-col gap-2">
<p>
<b>Is Text Truncated:</b> {itsTruncatedValue ? "Yes" : "No"}
</p>
<div className="h-10 w-40 overflow-hidden whitespace-nowrap">
<p className="truncate" ref={refOfValue}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
quas, quos, quae, quia quidem quibusdam
</p>
</div>
</div>
<div className="flex flex-col gap-2">
<p>
<b>Is Text Truncated:</b> {notTruncatedValue ? "Yes" : "No"}
</p>
<div className="whitespace-nowrap">
<p ref={refOfValue2}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
quas, quos, quae, quia quidem quibusdam
</p>
</div>
</div>
</div>
);
}
Code
import { type RefObject, useEffect, useRef, useState } from "react";
/**
* @description A hook that checks if the text content of an element is truncated or not.
* @param {RefObject<HTMLElement>} ref A reference to the element to check if its text is truncated.
* @returns {boolean} A boolean indicating if the text is truncated or not.
*/
export default function useIsTextTruncated(ref: RefObject<HTMLElement>) {
const [textTruncated, setTextTruncated] = useState<boolean>(false);
const prevContentRef = useRef<string | null>(null);
useEffect(() => {
const element = ref.current;
if (element) {
const currentContent = element.textContent || "";
if (prevContentRef.current !== currentContent) {
prevContentRef.current = currentContent;
}
if (element.scrollWidth > element.offsetWidth) {
setTextTruncated(true);
} else {
setTextTruncated(false);
}
}
}, [ref, ref.current?.textContent]);
return textTruncated;
}