Skip to content

Instantly share code, notes, and snippets.

@lucasrabiec
Last active November 25, 2022 14:39
Show Gist options
  • Save lucasrabiec/71e4c09ffbbe9074e9a158eb57587a52 to your computer and use it in GitHub Desktop.
Save lucasrabiec/71e4c09ffbbe9074e9a158eb57587a52 to your computer and use it in GitHub Desktop.
React's Hook for detecting whether the text is truncated or not. It is useful if you need to show a tooltip with full-length text.
import { useEffect, useRef, useState } from 'react';
export function useIsEllipsisActive() {
const textRef = useRef<HTMLParagraphElement>(null);
const [isEllipsisActive, setIsEllipsisActive] = useState(false);
const [rerenderSignal, setRerenderSignal] = useState({});
// Instead of this method you can use some useDebounce hook (if your project includes any).
function debounce(cb: (...args: unknown[]) => void, wait: number) {
let timer: number;
return (...args: unknown[]) => {
clearTimeout(timer);
timer = window.setTimeout(() => cb(...args), wait);
};
}
const handleResize = debounce(() => setRerenderSignal({}), 300);
useEffect(() => {
const element = textRef.current;
window.addEventListener('resize', handleResize);
setIsEllipsisActive(
element
? element.offsetWidth < element.scrollWidth ||
element.offsetHeight < element.scrollHeight
: false,
);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [rerenderSignal, handleResize]);
return {
textRef,
isEllipsisActive,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment