// from radix // https://raw.githubusercontent.com/radix-ui/primitives/main/packages/react/compose-refs/src/composeRefs.tsx import * as React from 'react' type PossibleRef = | React.Ref | React.ForwardedRef | React.RefObject | React.Dispatch> | undefined /** * Set a given ref to a given value * This utility takes care of different types of refs: callback refs and RefObject(s) */ export function setRef(ref: PossibleRef, value: T) { if (typeof ref === 'function') { ref(value) } else if (ref) { ;(ref as React.MutableRefObject).current = value } } /** * A utility to compose multiple refs together * Accepts callback refs and RefObject(s) */ export function composeRefs(...refs: PossibleRef[]) { return (node: T) => refs.forEach((ref) => setRef(ref, node)) } /** * A custom hook that composes multiple refs * Accepts callback refs and RefObject(s) */ export function useComposedRefs(...refs: PossibleRef[]) { return React.useCallback(composeRefs(...refs), refs) }