Last active
November 25, 2022 14:46
-
-
Save gubser/5f62d7853afaa0304b6eb8054852cee1 to your computer and use it in GitHub Desktop.
React hook for ResizeObserver. Adapted from https://github.com/Gautam-Arora24/resize-observer-hook/blob/master/src/index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from https://github.com/Gautam-Arora24/resize-observer-hook/blob/master/src/index.js | |
type UseResizeObserverMode = 'borderBoxSize'|'contentBoxSize'|'contentRect'; | |
export function useResizeObserver<T extends Element>(option: UseResizeObserverMode = 'contentRect') | |
: [React.MutableRefObject<T|null>, number|undefined, number|undefined] { | |
const ref = useRef<T|null>(null); | |
const [height, setHeight] = useState<number|undefined>(); | |
const [width, setWidth] = useState<number|undefined>(); | |
const handleResize: ResizeObserverCallback = useCallback(entries => { | |
for (const entry of entries) { | |
if (option === 'borderBoxSize' && entry.borderBoxSize.length > 0) { | |
setHeight(entry.borderBoxSize[0].blockSize); | |
setWidth(entry.borderBoxSize[0].inlineSize); | |
} else if (option === 'contentBoxSize' && entry.contentBoxSize.length > 0) { | |
setHeight(entry.contentBoxSize[0].blockSize); | |
setWidth(entry.contentBoxSize[0].inlineSize); | |
} else { | |
setHeight(entry.contentRect.height); | |
setWidth(entry.contentRect.width); | |
} | |
} | |
}, [option]); | |
useEffect(() => { | |
if (ref.current) { | |
const observer = new ResizeObserver((entries) => { | |
handleResize(entries, observer); | |
}); | |
observer.observe(ref.current); | |
// Callback fired when component is unmounted | |
return () => { | |
observer.disconnect(); | |
}; | |
} | |
// Added this return for eslint rule -> no-consisten-return | |
return undefined; | |
}, [handleResize]); | |
return [ref, width, height]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment