ZeeCoder / use-resize-observer

A React hook that allows you to use a ResizeObserver to measure an element's size.
MIT License
651 stars 42 forks source link

How should I use the use-resize-observer in case of useCallback instead of useRef #45

Closed terpimost closed 4 years ago

terpimost commented 4 years ago

What if I have useCallback instead of useRef, according to https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

const MyComponent = () => {
    const editorContainerRef = useCallback( editorContainer =>{
        //editorContainer here is a dom node already
    },[])

   return React.createElement('div',{
        ref: editorContainerRef,
        id: 'editor-container',
    })
}

I probably can fake it by creating {current:editorContainer} and passing that to usResizeObserver like this

const { width, height } = useResizeObserver({ ref: {current:editorContainer} as React.RefObject<HTMLElement> });

but may be there is a different approach?

ZeeCoder commented 4 years ago

I'm not sure why you can't just use a regular ref in this case? The link you point to is just using a so-called callback ref to receive an element, and then use its native methods to get its height.

If you only have an element for some reason that you need to measure, then, you should be able to "fake" a react-managed ref, something like this:

const MyComponent = () => {
    const [fakeRef, setFakeRef] = useState(null);
    const {width, height} = useResizeObserver({ref: fakeRef});
    const callbackRef= useCallback( editorContainer =>{
        setFakeRef({ current: editorContainer });
    },[])

   return React.createElement('div',{
        ref: callbackRef,
        id: 'editor-container',
    })
}

I haven't tested this though, and it's a really roundabout way of doing it.

On a related note: I'm slowly getting closer to releasing a new version of this lib, which'll accept refs callback refs and native elements as well.

ZeeCoder commented 4 years ago

Addressed in: https://github.com/ZeeCoder/use-resize-observer/releases/tag/v6.2.0-alpha.1

Now you can use the returned callbackRef for this: https://github.com/ZeeCoder/use-resize-observer#observing-components-mounted-with-a-delay