Closed niieani closed 3 years ago
Yes, I think this is a great idea 👍
Some random thoughts:
ref
when you pass it, otherwise it creates its own ref https://github.com/maslianok/react-resize-detector/blob/master/src/useResizeDetector.ts#L34targetRef
as a prop to set the observable element manually. To make it consistent I would recommend taking the same name https://github.com/maslianok/react-resize-detector/blob/master/src/ResizeDetector.tsx#L101Will you work on it? Let me know if you need any additional help
Added in v6.3.0
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const targetRef = userRef();
const { width, height } = useResizeDetector({ targetRef });
return <div ref={targetRef}>{`${width}x${height}`}</div>;
};
Oops, sorry I didn't have the time to get back to you! Thanks for the quick add @maslianok! 🙇
Looking at the change here 👀: https://github.com/maslianok/react-resize-detector/blob/662238b7f488542f0fd0662180db7fbe34178cbd/src/useResizeDetector.ts#L29
This might potentially cause issues, since it's a conditional use of the useRef
hook. Might be safer to always allocate the ref in the hook, and simply not use it when passed in.
Should we rewrite it to
const ref = useRef(null);
if (targetRef) {
ref.current = targetRef.current;
}
?
Interesting, I haven't thought of syncing them. Perhaps it might be simpler/safer to do this instead:
const localRef = useRef(null);
const ref = targetRef ?? localRef;
The localRef
will always be allocated, but if targetRef is passed in, it will be used instead.
Sold :)
tbh, I don't see any difference between these approaches. Just 2 lines instead of the 1-line condition.
Can you make a PR?
Thanks, merged!
I'll deploy changes in the next version
Hi @maslianok!
I'm faced with a conundrum: I need to access the
ref
inside theonResize
callback. But... I don't have theref
yet when I'm defining theonResize
, because it is the hook creates it 😕.A solution would be to allow passing in your own
ref
instead of creating it inside the hook. This way theref
could also be reused by other custom hooks that are used beforeuseResizeDetector
is called, like so:I'm willing to make a PR if this solution is fine by you. Thanks 🙇.