Spaces:
Sleeping
Sleeping
| import { useEffect, useState, type RefObject } from 'react' | |
| type ElementSize = { | |
| width: number | |
| height: number | |
| } | |
| export function useElementSize<T extends HTMLElement>( | |
| ref: RefObject<T | null>, | |
| ): ElementSize { | |
| const [size, setSize] = useState<ElementSize>({ width: 0, height: 0 }) | |
| useEffect(() => { | |
| const element = ref.current | |
| if (!element) { | |
| return | |
| } | |
| const observer = new ResizeObserver((entries) => { | |
| const entry = entries[0] | |
| if (!entry) { | |
| return | |
| } | |
| const nextWidth = Math.round(entry.contentRect.width) | |
| const nextHeight = Math.round(entry.contentRect.height) | |
| setSize((current) => { | |
| if (current.width === nextWidth && current.height === nextHeight) { | |
| return current | |
| } | |
| return { | |
| width: nextWidth, | |
| height: nextHeight, | |
| } | |
| }) | |
| }) | |
| observer.observe(element) | |
| return () => { | |
| observer.disconnect() | |
| } | |
| }, [ref]) | |
| return size | |
| } | |