Last active
August 16, 2024 02:21
-
-
Save wojtekmaj/3848f00c1dc78bfa0686bec96fef9608 to your computer and use it in GitHub Desktop.
Merge multiple React refs to use them on a single React element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome - thank you!