-
-
Save fedikhatib/ad295645f0472fc103e73a335ef026fe to your computer and use it in GitHub Desktop.
Merge refs in React so a component can have more than one ref
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 function mergeRefs(refs) { | |
return (value) => { | |
refs.forEach((ref) => { | |
if (typeof ref === "function") { | |
ref(value); | |
} else if (ref != null) { | |
ref.current = value; | |
} | |
}); | |
}; | |
} | |
///////////////////// | |
/////// Usage /////// | |
///////////////////// | |
const SomeComponent = forwardRef((props, ref) => { | |
const someOtherRef = React.useRef(); | |
return <div ref={mergeRefs([someOtherRef, ref])} />; | |
}); | |
// Note: | |
// This repo does basically the same thing, but it's TypeScript-y, | |
// so it might be "safer" or whatever | |
// https://github.com/gregberge/react-merge-refs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment