// from radix // https://raw.githubusercontent.com/radix-ui/primitives/main/packages/react/compose-refs/src/composeRefs.tsx import * as React from 'react' import type { ReactNode, Ref } from 'react' type PossibleRef = | React.Ref | 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) } export type RefProp = { ref?: Ref } export type RefComponent = (( props: Props & RefProp ) => ReactNode) & { displayName?: string propTypes?: any } export function createRefComponent( render: (props: Props, ref: Ref | undefined) => ReactNode ): RefComponent { function RefComponent(props: Props & RefProp) { const { ref, ...rest } = props return render(rest as Props, ref) } RefComponent.displayName = render.name return RefComponent as RefComponent }