Skip to content

Instantly share code, notes, and snippets.

@domosedov
Last active December 13, 2021 17:17
Show Gist options
  • Save domosedov/bdbfb4fe8204303d1f3e67f605c84d29 to your computer and use it in GitHub Desktop.
Save domosedov/bdbfb4fe8204303d1f3e67f605c84d29 to your computer and use it in GitHub Desktop.
React Typescript merge refs util
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