about summary refs log tree commit diff
path: root/src/lib/merge-refs.ts
diff options
context:
space:
mode:
authorPaul Frazee <pfrazee@gmail.com>2023-05-25 21:17:11 -0500
committerPaul Frazee <pfrazee@gmail.com>2023-05-25 21:17:11 -0500
commit7b6948e6171b448e271f0564efd1f186ccadb9b8 (patch)
treee0d1b6e9f9c863cbff53f8832fd55d03cb670a83 /src/lib/merge-refs.ts
parent15c1b6ee157471807a723161066ba4ce5e12c0b5 (diff)
parente832352e9844002408b45291396a3c495be23276 (diff)
downloadvoidsky-7b6948e6171b448e271f0564efd1f186ccadb9b8.tar.zst
Merge branch 'custom-algos' into main
Diffstat (limited to 'src/lib/merge-refs.ts')
-rw-r--r--src/lib/merge-refs.ts27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/lib/merge-refs.ts b/src/lib/merge-refs.ts
new file mode 100644
index 000000000..4617b5260
--- /dev/null
+++ b/src/lib/merge-refs.ts
@@ -0,0 +1,27 @@
+/**
+ * This TypeScript function merges multiple React refs into a single ref callback.
+ * When developing low level UI components, it is common to have to use a local ref
+ * but also support an external one using React.forwardRef.
+ * Natively, React does not offer a way to set two refs inside the ref property. This is the goal of this small utility.
+ * Today a ref can be a function or an object, tomorrow it could be another thing, who knows.
+ * This utility handles compatibility for you.
+ * This function is inspired by https://github.com/gregberge/react-merge-refs
+ * @param refs - An array of React refs, which can be either `React.MutableRefObject<T>` or
+ * `React.LegacyRef<T>`. These refs are used to store references to DOM elements or React components.
+ * The `mergeRefs` function takes in an array of these refs and returns a callback function that
+ * @returns The function `mergeRefs` is being returned. It takes an array of mutable or legacy refs and
+ * returns a ref callback function that can be used to merge multiple refs into a single ref.
+ */
+export function mergeRefs<T = any>(
+  refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>,
+): React.RefCallback<T> {
+  return value => {
+    refs.forEach(ref => {
+      if (typeof ref === 'function') {
+        ref(value)
+      } else if (ref != null) {
+        ;(ref as React.MutableRefObject<T | null>).current = value
+      }
+    })
+  }
+}