Skip to content

Instantly share code, notes, and snippets.

@Sensiblemnd
Forked from nkint/isTruncated.tsx
Created March 20, 2025 21:02
Show Gist options
  • Select an option

  • Save Sensiblemnd/ab4a6b5ac6ce1d2fb4a9a532e3de3302 to your computer and use it in GitHub Desktop.

Select an option

Save Sensiblemnd/ab4a6b5ac6ce1d2fb4a9a532e3de3302 to your computer and use it in GitHub Desktop.

Revisions

  1. @nkint nkint renamed this gist May 4, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @nkint nkint created this gist May 4, 2021.
    26 changes: 26 additions & 0 deletions tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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;
    }