diff --git a/src/hooks/useResizeObserver/useResizeObserver.stories.tsx b/src/hooks/useResizeObserver/useResizeObserver.stories.tsx index 56cd839..4db99e5 100644 --- a/src/hooks/useResizeObserver/useResizeObserver.stories.tsx +++ b/src/hooks/useResizeObserver/useResizeObserver.stories.tsx @@ -35,7 +35,7 @@ export const Demo: Story = { return ( <> -

Resize the window to update the width of the elements

+

Resize the window to update

Enabled: {enabled.toString()};
Width: {elementRefWidth}; @@ -57,3 +57,45 @@ export const Demo: Story = { ); }, }; + +export const Options: Story = { + render() { + // Element 1 + const elementRef1 = useRef(null); + const [elementWidth1, setElementWidth1] = useState(Number.NaN); + + const onResizeElement1 = useCallback((entries: Array) => { + setElementWidth1(entries.at(0)?.borderBoxSize.at(0)?.inlineSize ?? Number.NaN); + }, []); + + useResizeObserver(elementRef1, onResizeElement1, { + box: 'border-box', + }); + + // Element 2 + const elementRef2 = useRef(null); + const [elementWidth2, setElementWidth2] = useState(Number.NaN); + + const onResizeElement2 = useCallback((entries: Array) => { + setElementWidth2(entries.at(0)?.contentBoxSize.at(0)?.inlineSize ?? Number.NaN); + }, []); + + useResizeObserver(elementRef2, onResizeElement2, { + box: 'content-box', + }); + + return ( + <> +

Resize the window to update

+
+
border-box
+ Width: {elementWidth1}; +
+
+
content-box
+ Width: {elementWidth2}; +
+ + ); + }, +}; diff --git a/src/hooks/useResizeObserver/useResizeObserver.ts b/src/hooks/useResizeObserver/useResizeObserver.ts index f20b672..e799c52 100644 --- a/src/hooks/useResizeObserver/useResizeObserver.ts +++ b/src/hooks/useResizeObserver/useResizeObserver.ts @@ -7,10 +7,12 @@ import { unref, type Unreffable } from '../../utils/unref/unref.js'; * * @param target - The target to observe * @param callback - The callback to fire when the element resizes + * @param options - The ResizeObserverOptions for the observed element */ export function useResizeObserver( target: Unreffable, callback?: ResizeObserverCallback | undefined, + options?: ResizeObserverOptions, ): void { useEffect(() => { const element = unref(target); @@ -20,10 +22,11 @@ export function useResizeObserver( } const resizeObserver = new ResizeObserver(callback); - resizeObserver.observe(element); + resizeObserver.observe(element, options); return () => { resizeObserver.disconnect(); }; - }, [target, callback]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [target, callback, ...Object.values(options ?? {})]); }