Skip to content

Instantly share code, notes, and snippets.

@themgoncalves
Last active August 17, 2020 12:42
Show Gist options
  • Save themgoncalves/c0819eecd76fd4221a65148d12155ed3 to your computer and use it in GitHub Desktop.
Save themgoncalves/c0819eecd76fd4221a65148d12155ed3 to your computer and use it in GitHub Desktop.
Working with multiple references on React - Typescript
import React from 'react';
type Mutable<T> = {
-readonly [k in keyof T]: T[k];
};
const mergeRefs = <T>(...refs: React.Ref<T>[]) => (value: T): void => {
for (let i = 0; i < refs.length; i += 1) {
const ref = refs[i];
if (typeof ref === 'function') {
ref(value);
} else if (ref) {
(ref as Mutable<React.RefObject<T>>).current = value;
}
}
};
export default mergeRefs;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment