Created
May 4, 2021 13:48
-
-
Save nkint/1407fe104ce2b5c291be8ccd851f3aa9 to your computer and use it in GitHub Desktop.
react hook is truncated
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 { 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