Created
March 27, 2024 05:47
-
-
Save livemehere/f61cefca9fef04a715f44cdc04fe13ea to your computer and use it in GitHub Desktop.
hook :: detect text line count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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