Created
February 15, 2021 10:58
Merge React ref's
This file contains 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
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