Skip to content

Instantly share code, notes, and snippets.

@envex
Created June 20, 2019 14:45
Show Gist options
  • Save envex/ec042ad0c3a3877bcdc320219b2913fe to your computer and use it in GitHub Desktop.
Save envex/ec042ad0c3a3877bcdc320219b2913fe to your computer and use it in GitHub Desktop.
import { useMemo, useEffect, MutableRefObject } from 'react';
export default function useResizeObserver(
targetNode: MutableRefObject<any>,
callback: (rect: DOMRect) => void,
) {
const observer = useMemo(
() =>
// Note: ResizeObserver comes back as unfound even
// this it's available, so for now I'm just going to
// ignore the error
// @ts-ignore
new ResizeObserver((entries) => {
for (const entry of entries) {
callback(entry.contentRect);
}
}),
[callback]
);
useEffect(
() => {
if (targetNode.current) {
observer.observe(targetNode.current);
return () => {
observer.disconnect();
};
}
return;
},
[targetNode.current]
);
}
// We need to push the list down based on the current size of
// the banner, which can change because the window is resizable
const resizeCallback = React.useCallback((rect) => {
if (listRef.current) {
listRef.current.style.transform = `translateY(${rect.height + OFFSET}px)`;
}
}, [listRef]);
React.useEffect(() => {
return () => {
// Reset the FileList bump when the banner is unmounted
listRef.current.style.transform = `translateY(0px)`;
};
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment