use-element-size

Returns element width and height and observes changes with ResizeObserver

Import

Usage

Resize textarea by dragging its right bottom corner

Width: 0, height: 0

import { useElementSize } from '@mantine/hooks';
import { rem } from '@mantine/core';

function Demo() {
  const { ref, width, height } = useElementSize();

  return (
    <>
      <textarea ref={ref} style={{ width: rem(400), height: rem(120) }} />
      <div>Width: {width}, height: {height}</div>
    </>
  );
}

API

use-element-size is a simpler version of use-resize-observer hook. Hook returns a ref object that should be passed to the observed element, and the element's height and width. On the first render (as well as during SSR), or when no element is being observed, width and height properties are equal to 0.

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

const { ref, width, height } = useElementSize();

Definition

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

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