Created
March 22, 2021 07:37
-
-
Save jbaiter/8410a118f80d9a7dbfb45953e1eb6aee to your computer and use it in GitHub Desktop.
mergeRefs: Merge multiple React Refs into a single one
This file contains hidden or 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
/** Merge multiple refs into a single one. | |
* | |
* Taken from https://www.davedrinks.coffee/how-do-i-use-two-react-refs/, type-hints by us | |
*/ | |
export function mergeRefs<T>( | |
...refs: (React.MutableRefObject<T> | React.Ref<T>)[] | |
): React.Ref<T> | null { | |
const filteredRefs = refs.filter(Boolean) | |
if (!filteredRefs.length) return null | |
if (filteredRefs.length === 0) return filteredRefs[0] | |
return (inst: T) => { | |
for (const ref of filteredRefs) { | |
if (typeof ref === 'function') { | |
ref(inst) | |
} else if (ref) { | |
;(ref as React.MutableRefObject<T>).current = inst | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment