Resize sensor
A ResizeSensor calls onResize when its child element changes size. It wraps the browser's ResizeObserver API.
Usage#
import { ResizeSensor } from "@clawscale/react";- The child must be a single DOM element, or a component that forwards its ref to one.
- If you attach your own ref to the child, pass the same ref as
targetRef. onResizeruns asynchronously, at most once per frame.
Examples#
Observed width#
Drag the lower right corner of the box. onResize receives a list of ResizeObserverEntry objects. contentRect.width is the width inside the padding.
import { ResizeSensor } from "@clawscale/react";
import { useState } from "react";
export default function ResizeSensorBasic() {
const [width, setWidth] = useState<number>();
return (
<ResizeSensor onResize={(entries) => setWidth(entries[0]?.contentRect.width)}>
<div
style={{
border: "1px dashed var(--cs-color-border-strong)",
borderRadius: "var(--cs-radius-md)",
maxWidth: "100%",
minWidth: 160,
overflow: "hidden",
padding: 16,
resize: "horizontal",
width: 320,
}}
>
Observed width: <strong>{width === undefined ? "measuring" : `${Math.round(width)} px`}</strong>
</div>
</ResizeSensor>
);
}Props interface#
interface ResizeSensorProps@clawscale/reactResizeSensor requires a single DOM element child and will error otherwise.
| Props | Description |
|---|---|
childrenrequired | React.JSX.ElementSingle child, must be an element and not a string or fragment. |
observeParents | boolean = falseIf true, all parent DOM elements of the container will also be observed for size changes. The array of entries passed to onResize will now contain an entry for each parent element up to the root of the document. |
onResizerequired | (entries: ResizeObserverEntry[]) => voidCallback invoked when the wrapped element resizes. |
targetRef | React.RefObject<HTMLElement>If you attach a ref to the child yourself when rendering it, you must pass the same value here (otherwise, ResizeSensor won't be able to attach its own). |