Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created May 27, 2021 20:42
Show Gist options
  • Select an option

  • Save jtmthf/60541c203da89a0ad9cd49ad5668ea14 to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/60541c203da89a0ad9cd49ad5668ea14 to your computer and use it in GitHub Desktop.
import { RefObject, useEffect, useState } from 'react';
export function useLineCount(ref: RefObject<HTMLElement>): number {
const [lines, setLines] = useState(0);
useEffect(() => {
const resizeObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
const elementHeight = (entry.target as HTMLElement).offsetHeight;
const lineHeight = parseInt(getComputedStyle(entry.target).lineHeight, 10);
setLines(elementHeight / lineHeight);
})
});
if (ref.current) {
resizeObserver.observe(ref.current)
}
return () => {
resizeObserver.disconnect();
}
}, [ref]);
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment