React utility to merge refs
npm install @kunukn/use-merge-refs
# or
# yarn add @kunukn/use-merge-refs
import React from 'react';
import {
useThisThing,
useThatThing,
useAwesomeThing,
} from 'some-3rd-party-lib';
import useMergeRefs from '@kunukn/use-merge-refs';
const MyComponent = () => {
// The 3rd party libs requires ref bindings.
const [ref1, componentHeight] = useThisThing();
const [ref2, componentWidth] = useThatThing();
const [ref3, componentPosition] = useAwesomeThing();
let mergedRefs = useMergeRefs(ref1, ref2, ref3);
// The 3rd party libs now all have access to the same element.
return (
<div ref={mergedRefs}>
<div>The height is: {componentHeight}</div>
<div>The width is: {componentWidth}</div>
<div>The position is: {componentPosition}</div>
</div>
);
};
// You can also use an array as the argument. e.g.
// useMergeRefs([ref1, ref2, ref3])
https://codesandbox.io/s/reactjs-mergeref-pattern-r1q2q
When you need multiple ref for the same Component. This helps merge the required refs to one callbackRef.
MIT