Last active
December 13, 2021 17:17
-
-
Save domosedov/bdbfb4fe8204303d1f3e67f605c84d29 to your computer and use it in GitHub Desktop.
React Typescript merge refs util
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
import type { LegacyRef, MutableRefObject, RefCallback } from 'react' | |
/** | |
* @example <div ref={mergeRefs(ref, innerRef)} /> | |
*/ | |
export default function mergeRefs<T = any>( | |
refs: Array<MutableRefObject<T> | LegacyRef<T>>, | |
): RefCallback<T> { | |
return value => { | |
refs.forEach(ref => { | |
if (typeof ref === 'function') { | |
ref(value) | |
} else if (ref != null) { | |
;(ref as MutableRefObject<T | null>).current = value | |
} | |
}) | |
} | |
} | |
// import * as React from "react"; | |
// export default function mergeRefs<T = any>( | |
// refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>> | |
// ): React.RefCallback<T> { | |
// return (value) => { | |
// refs.forEach((ref) => { | |
// if (typeof ref === "function") { | |
// ref(value); | |
// } else if (ref != null) { | |
// (ref as React.MutableRefObject<T | null>).current = value; | |
// } | |
// }); | |
// }; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment