Created
April 23, 2020 09:07
-
-
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
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
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