All files / src/hooks useElementWidth.ts

88.23% Statements 15/17
50% Branches 3/6
100% Functions 4/4
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                1350x 1350x   1350x 170x 170x 170x 170x 170x 2x 2x   170x 170x     1350x    
import { useLayoutEffect, useRef, useState } from "react";
 
/**
 * The rendered width of an element, kept current as it resizes.
 *
 * For a layout that depends on the room a component actually has rather
 * than on the window: the chat's width depends on whether the app's
 * navigation and the conversation list are showing, which no viewport
 * breakpoint can know. Measured in a layout effect, so the first paint
 * already uses it, then followed with a ResizeObserver. 0 until measured,
 * and wherever nothing lays out (jsdom), so callers treat 0 as unknown.
 */
export function useElementWidth<T extends HTMLElement>(): [
  React.RefObject<T>,
  number,
] {
  const ref = useRef<T>(null);
  const [width, setWidth] = useState(0);
 
  useLayoutEffect(() => {
    const element = ref.current;
    Iif (!element) return;
    setWidth(element.getBoundingClientRect().width);
    Iif (typeof ResizeObserver !== "function") return;
    const observer = new ResizeObserver((entries) => {
      const next = entries[0]?.contentRect.width;
      Eif (typeof next === "number") setWidth(next);
    });
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
 
  return [ref, width];
}