From d442a6a76b29d2b403a03bf1dc64db1090d9e5cf Mon Sep 17 00:00:00 2001 From: Valerii Sidorenko Date: Fri, 13 Sep 2024 20:54:24 +0200 Subject: [PATCH] fix(useElementSize): set initial size of the element (#1857) --- .../private/useElementSize/useElementSize.ts | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/hooks/private/useElementSize/useElementSize.ts b/src/hooks/private/useElementSize/useElementSize.ts index bd8dfeea87..db93a78879 100644 --- a/src/hooks/private/useElementSize/useElementSize.ts +++ b/src/hooks/private/useElementSize/useElementSize.ts @@ -4,7 +4,7 @@ import round from 'lodash/round'; import throttle from 'lodash/throttle'; const RESIZE_THROTTLE = 16; -const ROUND_PRESICION = 2; +const ROUND_PRECISION = 2; export interface UseElementSizeResult { width: number; @@ -24,10 +24,16 @@ export function useElementSize( }); React.useLayoutEffect(() => { - if (!ref?.current) { + const element = ref?.current; + if (!element) { return undefined; } + setSize({ + width: round(element.offsetWidth, ROUND_PRECISION), + height: round(element.offsetHeight, ROUND_PRECISION), + }); + const handleResize: ResizeObserverCallback = (entries) => { if (!Array.isArray(entries)) { return; @@ -42,20 +48,20 @@ export function useElementSize( // https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html#L88 setSize({ - width: round(borderBoxSize.inlineSize, ROUND_PRESICION), - height: round(borderBoxSize.blockSize, ROUND_PRESICION), + width: round(borderBoxSize.inlineSize, ROUND_PRECISION), + height: round(borderBoxSize.blockSize, ROUND_PRECISION), }); } else { const target = entry.target as HTMLElement; setSize({ - width: round(target.offsetWidth, ROUND_PRESICION), - height: round(target.offsetHeight, ROUND_PRESICION), + width: round(target.offsetWidth, ROUND_PRECISION), + height: round(target.offsetHeight, ROUND_PRECISION), }); } }; const observer = new ResizeObserver(throttle(handleResize, RESIZE_THROTTLE)); - observer.observe(ref.current); + observer.observe(element); return () => { observer.disconnect();