Is there any efficient way to show/hide text in an element based on its width?
For example, there is an element with a dynamic width that can change and the text displayed in it. I want the text to be displayed only when the width of the element is wide enough to show it completely, and to hide when it overflowing the element (no line breaks, only one line)
I tried to write a react component that would display such text, but it works for me only for a static width, when changing, the text does not disappear/appear. Also, I don’t like the way it’s done here:
const AdaptiveText: React.FC<Props> = ({ text }) => {
const textRef = useRef<HTMLDivElement>(null);
const [isOverflowing, setIsOverflowing] = useState(false);
useEffect(() => {
const checkOverflow = () => {
if (textRef.current) {
setIsOverflowing(textRef.current.scrollWidth > textRef.current.clientWidth);
}
};
checkOverflow();
window.addEventListener("resize", checkOverflow);
return () => {
window.removeEventListener("resize", checkOverflow);
};
}, [text]);
return (
<div
style={{
width: "100%",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
display: isOverflowing ? "none" : "block",
position: "relative",
}}
ref={textRef}
title={isOverflowing ? text : ""}
>
{text}
</div>
);
};