use-resize-observer

Tracks element size and position changes with ResizeObserver

Usage

Resize me!
Resize element by dragging its right bottom corner
PropertyValue
width0
height0
import { Text, Code } from '@mantine/core';
import { useResizeObserver } from '@mantine/hooks';

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

  return (
    <div className={classes.root}>
      <Group justify="center">
        <div ref={ref} className={classes.demo}>
          Resize me!
        </div>
      </Group>

      <Table
        captionSide="top"
        data={{
          caption: 'Resize element by dragging its right bottom corner',
          head: ['Property', 'Value'],
          body: [
            ['width', rect.width],
            ['height', rect.height],
          ],
        }}
      />
    </div>
  );
}

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

type ObserverRect = Omit<DOMRectReadOnly, 'toJSON'>;

function useResizeObserver<T extends HTMLElement = any>(
  options?: ResizeObserverOptions
): readonly [React.RefObject<T>, ObserverRect];