Skip to content

Instantly share code, notes, and snippets.

@srph
Created May 25, 2019 21:30
Show Gist options
  • Save srph/f41f29c938c60f1ae6ad4da5d12d8724 to your computer and use it in GitHub Desktop.
Save srph/f41f29c938c60f1ae6ad4da5d12d8724 to your computer and use it in GitHub Desktop.
React: Function to assign multiple refs to an element (compose refs)

Usage

const builderRef = useRef()

const [dropProps, dropRef] = useDrop({
  // ..
})

<div className="builder-content" ref={composeRefs([builderRef, dropRef])}>
</div>
function composeRefs<T>(refs: React.Ref<T>[]): React.Ref<T> {
return function(component: T) {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(component)
} else if (ref && 'current' in ref) {
ref.current = component
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment