Skip to content

Instantly share code, notes, and snippets.

@JayMGurav
Created February 15, 2021 10:58
Show Gist options
  • Save JayMGurav/ebf0a300f7727d08ede427bb8095b24a to your computer and use it in GitHub Desktop.
Save JayMGurav/ebf0a300f7727d08ede427bb8095b24a to your computer and use it in GitHub Desktop.
Merge React ref's
import React from 'react';
export default function mergeRefs(...refs){
const filteredRefs = refs.filter(Boolean);
return React.useMemo(() => {
if(!filteredRefs.length) return null;
return (node) => {
filteredRefs.forEach(ref => {
if(ref) assignRef(ref, node);
});
}
}, filteredRefs);
}
function assignRef(ref, value){
if(ref == null) return;
if(typeof ref === 'function'){
ref(value);
return;
}
try{
ref.current = value;
}catch(error){
throw new Error(`Cannot assign value ${value} to ref ${ref}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment