Skip to content

Instantly share code, notes, and snippets.

@fedikhatib
Forked from cassidoo/mergerefs.jsx
Created April 8, 2024 01:28
Show Gist options
  • Save fedikhatib/ad295645f0472fc103e73a335ef026fe to your computer and use it in GitHub Desktop.
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
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