Skip to content

Instantly share code, notes, and snippets.

@alexrdz
Created September 24, 2021 18:23
Show Gist options
  • Save alexrdz/fe50cb78e8daaf3c5016ece3ded913d0 to your computer and use it in GitHub Desktop.
Save alexrdz/fe50cb78e8daaf3c5016ece3ded913d0 to your computer and use it in GitHub Desktop.

Revisions

  1. alex rodriguez created this gist Sep 24, 2021.
    12 changes: 12 additions & 0 deletions useDimensions.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    const useRefDimensions = (ref: React.RefObject<HTMLDivElement>) => {
    const [dimensions, setDimensions] = useState({ width: 1, height: 2 })

    useEffect(() => {
    if (ref.current) {
    const boundingRect = ref.current.getBoundingClientRect();
    const { width, height } = boundingRect;
    setDimensions({ width: Math.round(width), height: Math.round(height) })
    }
    }, [ref])
    return dimensions
    }