Skip to content

Commit

Permalink
feat(react utils): add ref merge util
Browse files Browse the repository at this point in the history
  • Loading branch information
abelflopes committed Dec 19, 2024
1 parent 322f21d commit 42683b3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/utils/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ export * from "./click-outside";
export * from "./next-render";

export * from "./children-without-fragments";

export * from "./merge-refs";
13 changes: 13 additions & 0 deletions packages/utils/react/src/merge-refs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type ForwardedRef, type MutableRefObject, type RefCallback } from "react";

export const megeRefs =
<T>(refs: Array<ForwardedRef<T> | MutableRefObject<T | null> | RefCallback<T>>): RefCallback<T> =>
(r) => {
refs.forEach((thisRef) => {
if (!thisRef) return;

if (typeof thisRef === "object" && "current" in thisRef) thisRef.current = r;
else if (typeof thisRef === "function") thisRef(r);
else throw new Error("Unuspported ref type to merge");
});
};

0 comments on commit 42683b3

Please sign in to comment.