Skip to content

Instantly share code, notes, and snippets.

@jbaiter
Created March 22, 2021 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbaiter/8410a118f80d9a7dbfb45953e1eb6aee to your computer and use it in GitHub Desktop.
Save jbaiter/8410a118f80d9a7dbfb45953e1eb6aee to your computer and use it in GitHub Desktop.
mergeRefs: Merge multiple React Refs into a single one
/** 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