Last active
August 21, 2021 05:21
-
-
Save ajitid/379fce94d2531d7c21a6acd2cc54b690 to your computer and use it in GitHub Desktop.
Merge references
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
import type { MutableRefObject } from 'react'; | |
type References<T extends HTMLElement = HTMLElement> = | |
| MutableRefObject<unknown> | |
| ((element: T | null) => void) | |
| undefined | |
| null; | |
/** | |
* Utility function that let's you assign multiple references to a 'ref' prop | |
* @param refs list of MutableRefObject's and/or callbacks | |
*/ | |
export function mergeReferences<T extends HTMLElement = HTMLElement>( | |
// Suppressing ESLint as the function assigns `MutableRefObject` a value. | |
// eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types | |
...references: References<T>[] | |
) { | |
return (element: T | null) => { | |
for (const ref of references) { | |
if (!ref) { | |
continue; | |
} | |
if (typeof ref === 'function') { | |
ref(element); | |
} else { | |
ref.current = element; | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment