Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active August 16, 2024 02:21
Show Gist options
  • Save wojtekmaj/3848f00c1dc78bfa0686bec96fef9608 to your computer and use it in GitHub Desktop.
Save wojtekmaj/3848f00c1dc78bfa0686bec96fef9608 to your computer and use it in GitHub Desktop.
Merge multiple React refs to use them on a single React element.
/**
* Allows to use multiple refs on a single React element.
* Supports both functions and ref objects created using createRef() and useRef().
*
* Usage:
* ```jsx
* <div ref={mergeRefs(ref1, ref2, ref3)} />
* ```
*
* @param {...Array<Function|Object>} inputRefs Array of refs
*/
function mergeRefs(...inputRefs) {
return (ref) => {
inputRefs.forEach((inputRef) => {
if (!inputRef) {
return;
}
if (typeof inputRef === 'function') {
inputRef(ref);
} else {
// eslint-disable-next-line no-param-reassign
inputRef.current = ref;
}
});
};
}
@rstruthers1
Copy link

This is awesome - thank you!

@wojtekmaj
Copy link
Author

@rstruthers1 Improved, typed version is published on npm!

https://www.npmjs.com/package/merge-refs

@dariadmitrochenko
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment