Skip to content

Instantly share code, notes, and snippets.

@ellemedit
Created April 23, 2020 09:07
Show Gist options
  • Save ellemedit/0698b67daa49c90d0a19c06cd03d0551 to your computer and use it in GitHub Desktop.
Save ellemedit/0698b67daa49c90d0a19c06cd03d0551 to your computer and use it in GitHub Desktop.
sometimes you have to deal with multiple React.Refs. This is short helper
export const combineRef = <T>(...refs: (React.Ref<T> | string | void)[]) => {
// basically, JSX elements allows string refs for backward-compatiblity
// there's certain case runtime check needed
if (process.env.NODE_ENV !== "production" && refs.some((x) => typeof x === "string")) {
throw new Error("string refs are forbbiden");
}
return (node: T | null | undefined) => {
for (const ref of refs) {
if (!ref || typeof ref === "string") {
continue;
}
setRef(ref, node);
}
};
};
const setRef = <T>(ref: React.Ref<T>, node: T) => {
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as any).current = node;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment