merge-refs

v1.3.0
A function that merges React refs into one.
react react ref react refs merge

npm downloads CI

Merge-Refs

A function that merges React refs into one. Filters out invalid (eg. falsy) refs as well and returns original ref if only one valid ref was given.

tl;dr

  • Install by executing npm install merge-refs or yarn add merge-refs.
  • Import by adding import mergeRefs from 'merge-refs'.
  • Use it in ref like so: <div ref={mergeRefs(ref, someOtherRef)} />

Accepted refs

  • Refs created using createRef()
  • Refs created using useRef()
  • Functional refs

Example

function Hello() {
  const ref1 = useRef<HTMLDivElement>(); // I'm going to be updated!
  const ref2 = (element: HTMLDivElement) => {
    // I'm going to be called!
  };

  return <div ref={mergeRefs(ref1, ref2)} />;
}

License

The MIT License.

Author

Wojciech Maj Wojciech Maj
npm i merge-refs

Metadata

  • MIT
  • Whatever
  • Wojciech Maj
  • released 4/30/2024

Downloads

Maintainers