compose-refs
diceui-radix/compose-refsFreeUtility
diceui/radix publishes no description for this item.
Install it
npx shadcn@latest add https://raw.githubusercontent.com/sadmann7/diceui/HEAD/docs/public/r/styles/radix-nova/compose-refs.jsonSource
1/**2 * @see https://github.com/radix-ui/primitives/blob/main/packages/react/compose-refs/src/compose-refs.tsx3 */45import * as React from "react";67type PossibleRef<T> = React.Ref<T> | undefined;89/**10 * Set a given ref to a given value11 * This utility takes care of different types of refs: callback refs and RefObject(s)12 */13function setRef<T>(ref: PossibleRef<T>, value: T) {14 if (typeof ref === "function") {15 return ref(value);16 }1718 if (ref !== null && ref !== undefined) {19 ref.current = value;20 }21}2223/**24 * A utility to compose multiple refs together25 * Accepts callback refs and RefObject(s)26 */27function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {28 return (node) => {29 let hasCleanup = false;30 const cleanups = refs.map((ref) => {31 const cleanup = setRef(ref, node);32 if (!hasCleanup && typeof cleanup === "function") {33 hasCleanup = true;34 }35 return cleanup;36 });3738 // React <19 will log an error to the console if a callback ref returns a39 // value. We don't use ref cleanups internally so this will only happen if a40 // user's ref callback returns a value, which we only expect if they are41 // using the cleanup functionality added in React 19.42 if (hasCleanup) {43 return () => {44 for (let i = 0; i < cleanups.length; i++) {45 const cleanup = cleanups[i];46 if (typeof cleanup === "function") {47 cleanup();48 } else {49 setRef(refs[i], null);50 }51 }52 };53 }54 };55}5657/**58 * A custom hook that composes multiple refs59 * Accepts callback refs and RefObject(s)60 */61function useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {62 // biome-ignore lint/correctness/useExhaustiveDependencies: we want to memoize by all values63 return React.useCallback(composeRefs(...refs), refs);64}6566export { composeRefs, useComposedRefs };
Files it writes
More from diceui/radix
All 58 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| utilsutils | diceui/radix | Utilities | Free | 2 deps |
