-
-
Save Sensiblemnd/ab4a6b5ac6ce1d2fb4a9a532e3de3302 to your computer and use it in GitHub Desktop.
react hook is truncated
This file contains hidden or 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 { useLayoutEffect, useState } from 'react'; | |
/** | |
* Determine if the input DOM element is truncated by CSS (using ellipse for example) | |
* @param domElement | |
* @returns boolean | |
*/ | |
export function isTruncated(domElement: Element): boolean { | |
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth | |
return domElement.scrollWidth > domElement.clientWidth; | |
} | |
export function useIsTruncated<T extends Element>(ref: React.MutableRefObject<null | T>): boolean { | |
const [isTruncatedState, setIsTruncatedState] = useState(false); | |
useLayoutEffect(() => { | |
if (ref.current !== null) { | |
const isTextTruncated = isTruncated(ref.current); | |
if (isTruncatedState !== isTextTruncated) { | |
setIsTruncatedState(isTextTruncated); | |
} | |
} | |
}, [isTruncatedState, ref]); | |
return isTruncatedState; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment