@dschz/solid-auto-sizer
Version:
SolidJS component that automatically measures and provides the width and height of its parent — useful for virtualized lists, grids, and charts.
57 lines (56 loc) • 1.4 kB
JSX
// src/AutoSizer.tsx
import { createSignal, mergeProps, onCleanup, onMount } from "solid-js";
var AutoSizer = (props) => {
let container;
const _props = mergeProps(
{
initialWidth: 0,
initialHeight: 0
},
props
);
const [size, setSize] = createSignal({
width: _props.initialWidth,
height: _props.initialHeight
});
onMount(() => {
const containerRect = container.getBoundingClientRect();
const containerSize = {
width: Math.floor(containerRect.width),
height: Math.floor(containerRect.height)
};
if (containerSize.width !== size().width || containerSize.height !== size().height) {
setSize(containerSize);
_props.onResize?.(containerSize);
}
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries[0];
if (!entry) return;
const { width, height } = entry.contentRect;
const newSize = {
width: Math.floor(width),
height: Math.floor(height)
};
setSize(newSize);
_props.onResize?.(newSize);
});
resizeObserver.observe(container);
onCleanup(() => {
resizeObserver.disconnect();
});
});
return <div
ref={container}
class={_props.class}
style={{
width: "100%",
height: "100%",
..._props.style
}}
>
{_props.children(size())}
</div>;
};
export {
AutoSizer
};