diff --git a/README.md b/README.md index 8bf59aa..5db624d 100644 --- a/README.md +++ b/README.md @@ -9,12 +9,19 @@ yarn add @rehooks/component-size ## Usage ```js -import { useRef } from 'react' +import { useRef, useState } from 'react' import useComponentSize from '@rehooks/component-size' function MyComponent() { - let ref = useRef(null) - let size = useComponentSize(ref) + const [imgElem, setImageElem] = useState(null); + // callback ref to ensure re-render when ref is set, as per React docs + // https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node + let ref = useCallback(elem => { + if (elem !== null) { + setImgElem(elem) + } + }, []) + let size = useComponentSize(imgElem) // size == { width: 100, height: 200 } let { width, height } = size let imgUrl = `https://via.placeholder.com/${width}x${height}` diff --git a/index.d.ts b/index.d.ts index 8d655d4..e094c02 100644 --- a/index.d.ts +++ b/index.d.ts @@ -3,4 +3,4 @@ interface ComponentSize { height: number } -export default function useComponentSize(ref: React.RefObject): ComponentSize +export default function useComponentSize(ref: T | React.RefObject): ComponentSize diff --git a/index.js b/index.js index 5e652a2..c2b2efe 100644 --- a/index.js +++ b/index.js @@ -18,24 +18,29 @@ function getSize(el) { } } -function useComponentSize(ref) { - var _useState = useState(getSize(ref ? ref.current : {})) +function useComponentSize(elemOrRef) { + const el = elemOrRef && ( + elemOrRef instanceof Element || elemOrRef instanceof HTMLDocument + ? elemOrRef + : elemOrRef.current + ); + var _useState = useState(getSize(el)) var ComponentSize = _useState[0] var setComponentSize = _useState[1] var handleResize = useCallback( function handleResize() { - if (ref.current) { - setComponentSize(getSize(ref.current)) + if (el) { + setComponentSize(getSize(el)) } }, - [ref] + [el] ) useLayoutEffect( function() { - if (!ref.current) { - return + if (!el) { + return; } handleResize() @@ -44,10 +49,10 @@ function useComponentSize(ref) { var resizeObserver = new ResizeObserver(function() { handleResize() }) - resizeObserver.observe(ref.current) + resizeObserver.observe(el) return function() { - resizeObserver.disconnect(ref.current) + resizeObserver.disconnect(el) resizeObserver = null } } else { @@ -58,7 +63,7 @@ function useComponentSize(ref) { } } }, - [ref.current] + [el] ) return ComponentSize diff --git a/index.js.flow b/index.js.flow index 18dc8a8..10c95c0 100644 --- a/index.js.flow +++ b/index.js.flow @@ -3,4 +3,4 @@ interface ComponentSize { height: number, } -declare export default function useComponentSize(ref: React.Ref): ComponentSize; \ No newline at end of file +declare export default function useComponentSize(ref: T | React.Ref): ComponentSize; \ No newline at end of file