Skip to content

Instantly share code, notes, and snippets.

@livemehere
Created March 27, 2024 05:47
Show Gist options
  • Save livemehere/f61cefca9fef04a715f44cdc04fe13ea to your computer and use it in GitHub Desktop.
Save livemehere/f61cefca9fef04a715f44cdc04fe13ea to your computer and use it in GitHub Desktop.
hook :: detect text line count
import { RefObject, useEffect, useState } from 'react';
const useDetectTextLine = (target: RefObject<HTMLElement>) => {
const [line, setLine] = useState<number>();
useEffect(() => {
const el = target.current;
if (!el) return;
const observer = new ResizeObserver((entries) => {
entries.forEach((entry) => {
const lh = parseInt(getComputedStyle(entry.target).lineHeight);
const newH = entry.contentRect.height;
setLine(newH / lh);
});
});
observer.observe(el);
return () => {
observer.disconnect();
};
}, []);
return line;
};
export default useDetectTextLine;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment