-
-
Notifications
You must be signed in to change notification settings - Fork 421
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use ResizeObserver
for useElementSize
#236
Comments
The values returned by ReiszeObserver don't include padding/border. Something like this would better match the existing behavior: export const useElementSize = <T extends HTMLElement = HTMLDivElement>(): [
RefObject<T>,
Size
] => {
const ref = useRef<T>(null);
const [size, setSize] = useState<Size>({
width: 0,
height: 0,
});
useIsomorphicLayoutEffect(() => {
const updateSize = (element: Element | null) => {
const { width, height } = element?.getBoundingClientRect() ?? {
width: 0,
height: 0,
};
setSize({ width, height });
};
updateSize(ref.current);
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries[0];
if (entry) {
updateSize(entry.target);
}
});
ref.current && resizeObserver.observe(ref.current);
return () => {
ref.current && resizeObserver.unobserve(ref.current);
};
}, [ref.current]);
return [ref, size];
}; |
I had a similar issue with |
Hi, |
The
useElementSize
hook doesn't react to changes in the size of the element during CSS animations, instead it jumps to the final size instantaneously. This becauseuseEventListener('resize', handleSize)
listens towindow
resize events, and not actually element resize events.I'd like to propose using
ResizeObserver
for this hook instead of the current implementation.ResizeObserver
is supported by all modern browsers, only IE used to block it but it's now reached end of life (and it can be polyfilled). If it will be of interest I will work on a PR.I also think it might be OK to use
useRef
instead of manually managing the ref instance. If the element the ref points to changes I think that would re-render this hook in most if not all cases. Related issues are #196, #205, #217The text was updated successfully, but these errors were encountered: