Skip to content

Instantly share code, notes, and snippets.

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