use-resize-observer

Subscribe to element size and position changes with ResizeObserver
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 { useMantineTheme, Text, Code } from '@mantine/core';
import { useResizeObserver } from '@mantine/hooks';
function Demo() {
const theme = useMantineTheme();
const [ref, rect] = useResizeObserver();
return (
<>
<textarea ref={ref} style={{ width: 400, height: 120 }} />
<Text align="center">Rect: <Code>{JSON.stringify(rect)}</Code></Text>
</>
);
}

API

Hook returns 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.

const [ref, rect] = useResizeObserver();
<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;
}
];
Build fully functional accessible web applications faster than ever
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback