use-resize-observer

Tracks element size and position changes

Import

Usage

Resize textarea by dragging its right bottom corner

Rect: { "x": 0, "y": 0, "width": 0, "height": 0, "top": 0, "left": 0, "bottom": 0, "right": 0 }

import { Text, Code, rem } from '@mantine/core';
import { useResizeObserver } from '@mantine/hooks';

function Demo() {
  const [ref, rect] = useResizeObserver();

  return (
    <>
      <textarea ref={ref} style={{ width: rem(400), height: rem(120) }} />
      <Text ta="center">Rect: <Code>{JSON.stringify(rect)}</Code></Text>
    </>
  );
}

API

use-resize-observer returns a ref object that should be passed to the observed element, and the current element content rect, as returned by ResizeObserver's callback entry.contentRect. See Resize Observer API documentation to learn more. On the first render (as well as during SSR), or when no element is being observed, all of the properties are equal to 0.

import { useResizeObserver } from '@mantine/hooks';

function Demo() {
  const [ref, rect] = useResizeObserver();
  return <div ref={ref}>Observed</div>;
}

See also use-element-size hook in case you need to subscribe only to width and height.

Definition

function useResizeObserver<T extends HTMLElement = any>(): [
  MutableRefObject<T>,
  {
    x: number;
    y: number;
    top: number;
    left: number;
    right: number;
    bottom: number;
    height: number;
    width: number;
  }
];