Get the amount of lines of an element.
npm i use-count-lines
Attach the ref to the element you want to count the lines
Demo:
See the storybook for an example with multiple texts
Or
Example.js
import { useCountLines } from 'use-count-lines';
export default function ExampleComponent({ children }) {
const { ref, lines } = useCountLines();
return <h1 ref={ref}>This header has {lines}</h1>;
}
If you already have a ref declared, you can pass to the hook and it will use that element.
import React from "react"
import { useCountLines } from "use-count-lines"
export default function ExampleComponent({ children }) {
const customRef = useRef():
const { lines } = useCountLines(customRef);
return <h1 ref={ref}>This header has {lines}</h1>
}
The useCountLines hook also returns other info that might be useful
import React from 'react';
import { useCountLines } from 'use-count-lines';
export default function ExampleComponent({ children }) {
const {
ref,
lines,
textHeight,
naturalHeightWithOneLine,
firstLineHeight,
additionalLineHeight,
} = useCountLines();
return <h1 ref={ref}>This header has {lines}</h1>;
}