@kunukn/use-merge-refs
TypeScript icon, indicating that this package has built-in type declarations

0.0.9 • Public • Published

use-merge-refs

npm version npm downloads gzip license

React utility to merge refs

npm install @kunukn/use-merge-refs
# or 
# yarn add @kunukn/use-merge-refs

Example

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])

Demo

https://codesandbox.io/s/reactjs-mergeref-pattern-r1q2q

Why?

When you need multiple ref for the same Component. This helps merge the required refs to one callbackRef.

License

MIT

Inspiration from:

https://github.com/smooth-code/react-merge-refs

Readme

Keywords

none

Package Sidebar

Install

npm i @kunukn/use-merge-refs

Weekly Downloads

10

Version

0.0.9

License

MIT

Unpacked Size

10.3 kB

Total Files

12

Last publish

Collaborators

  • kunukn