Skip to content

Instantly share code, notes, and snippets.

@cassidoo
Created January 10, 2023 22:57
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cassidoo/0b156d0f2eb154c43eeed3b1f212bb20 to your computer and use it in GitHub Desktop.
Save cassidoo/0b156d0f2eb154c43eeed3b1f212bb20 to your computer and use it in GitHub Desktop.
Merge refs in React so a component can have more than one ref
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