ZeeCoder / use-resize-observer

A React hook that allows you to use a ResizeObserver to measure an element's size.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

terpimost opened this issue · comments

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?

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.