Created
November 5, 2018 18:52
-
-
Save darthtrevino/b52cb9b7b9072def9353fd56f6a69d1f to your computer and use it in GitHub Desktop.
useDimensions Hook (Replace AutoSizer)
This file contains hidden or 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
// NOTE: Adapted from TS code, stripped types out | |
import React, { useRef, useState, useEffect } from 'react' | |
/** | |
* A custom hook that uses a resizeObserver to change dimension state | |
* @param defaultDimensions { width: number, height: number} | |
*/ | |
export function useDimensions(defaultDimensions) { | |
const [dimensions, setDimensions] = useState(defaultDimensions) | |
const ref = useRef() | |
useEffect( | |
() => { | |
const ro = new ResizeObserver(entries => { | |
for (const entry of entries) { | |
const { width, height } = entry.contentRect | |
setDimensions({ width, height }) | |
} | |
}) | |
ro.observe(ref.current) | |
return () => ro.disconnect() | |
}, | |
[ref], | |
) | |
return [dimensions, ref] | |
} | |
====== | |
const MainView = () => { | |
const [dimensions, viewspaceRef] = useDimensions({ | |
width: 500, | |
height: 500, | |
}) | |
return ( | |
<div> | |
<Controls /> | |
<div ref={viewspaceRef}> | |
<ViewSpace dimensions={dimensions} /> | |
</div> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment