Back to Mantine

Use Resize Observer

apps/mantine.dev/src/pages/hooks/use-resize-observer.mdx

9.3.21.2 KB
Original Source

import { UseResizeObserverDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';

export default Layout(MDX_DATA.useResizeObserver);

Usage

<Demo data={UseResizeObserverDemos.usage} />

API

The use-resize-observer hook returns a ref object that should be passed to the observed element, and the current element content rect, as returned by the ResizeObserver's callback entry.contentRect. See the 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.

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

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

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

Definition

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

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