Skip to content

Instantly share code, notes, and snippets.

@doubleedesign
Last active August 7, 2023 01:27
Show Gist options
  • Save doubleedesign/c530f6be756e2f4312192c28a10fa3da to your computer and use it in GitHub Desktop.
Save doubleedesign/c530f6be756e2f4312192c28a10fa3da to your computer and use it in GitHub Desktop.
React hook to keep text on one line, truncating it with an ellpisis if it's longer than its container's width. Demo: https://codesandbox.io/s/morning-butterfly-x8rxwy?file=/src/App.tsx
import { useState, useEffect, useMemo, MutableRefObject } from 'react';
import { useVisibleSize } from './useVisibleSize.ts';
export function useTruncatedText(outerRef: MutableRefObject<any>, innerRef: MutableRefObject<any>) {
const { width: outerWidth } = useVisibleSize(outerRef.current);
const { width: innerWidth } = useVisibleSize(innerRef.current);
useEffect(() => {
if (innerRef.current) {
innerRef.current.style.whiteSpace = "nowrap";
}
if (outerRef.current) {
outerRef.current.style.display = "flex";
}
if(typeof innerWidth !== 'undefined' && typeof outerWidth !== 'undefined' && (innerWidth > outerWidth)) {
innerRef.current.style.width = outerWidth;
innerRef.current.style.overflowX = 'hidden';
innerRef.current.style.textOverflow = 'ellipsis';
}
}, [outerWidth, innerWidth, outerRef, innerRef]);
return true;
}
import { useEffect, useMemo, useState } from 'react';
export function useVisibleSize(item: HTMLElement) {
const [width, setWidth] = useState<number>();
const [height, setHeight] = useState<number>();
const observer = useMemo(() => {
return new ResizeObserver((entries) => {
window.requestAnimationFrame(() => {
setWidth(entries[0].target.getBoundingClientRect().width);
setHeight(entries[0].target.getBoundingClientRect().height);
});
});
}, []);
useEffect(() => {
if (item) {
observer.observe(item);
return (): void => observer.unobserve(item);
}
}, [item, observer]);
return { width, height };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment