aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/helpers
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/helpers')
-rw-r--r--src/utils/helpers/index.ts1
-rw-r--r--src/utils/helpers/refs.test.tsx28
-rw-r--r--src/utils/helpers/refs.ts16
3 files changed, 45 insertions, 0 deletions
diff --git a/src/utils/helpers/index.ts b/src/utils/helpers/index.ts
index f340a49..79077de 100644
--- a/src/utils/helpers/index.ts
+++ b/src/utils/helpers/index.ts
@@ -2,6 +2,7 @@ export * from './author';
export * from './images';
export * from './pages';
export * from './reading-time';
+export * from './refs';
export * from './rss';
export * from './schema-org';
export * from './strings';
diff --git a/src/utils/helpers/refs.test.tsx b/src/utils/helpers/refs.test.tsx
new file mode 100644
index 0000000..93e5f89
--- /dev/null
+++ b/src/utils/helpers/refs.test.tsx
@@ -0,0 +1,28 @@
+import { describe, it, jest } from '@jest/globals';
+import { render } from '@testing-library/react';
+import { forwardRef, useImperativeHandle } from 'react';
+import { mergeRefs } from './refs';
+
+const refValue = 'minus architecto qui';
+const TestComponentWithForwardedRef = forwardRef((_, ref) => {
+ useImperativeHandle(ref, () => refValue);
+ return null;
+});
+TestComponentWithForwardedRef.displayName = 'TestComponentWithForwardedRef';
+
+describe('merge-refs', () => {
+ it('can merge a ref function with a ref object', () => {
+ const refFn = jest.fn();
+ const refObj = { current: null };
+
+ const TestComponent = () => (
+ <TestComponentWithForwardedRef ref={mergeRefs([refFn, refObj])} />
+ );
+
+ render(<TestComponent />);
+
+ expect(refFn).toHaveBeenCalledTimes(1);
+ expect(refFn).toHaveBeenLastCalledWith(refValue);
+ expect(refObj.current).toBe(refValue);
+ });
+});
diff --git a/src/utils/helpers/refs.ts b/src/utils/helpers/refs.ts
new file mode 100644
index 0000000..74a695a
--- /dev/null
+++ b/src/utils/helpers/refs.ts
@@ -0,0 +1,16 @@
+import type { LegacyRef, MutableRefObject, RefCallback } from 'react';
+import type { Nullable } from '../../types';
+
+export const mergeRefs =
+ <T = unknown>(
+ refs: (MutableRefObject<T> | LegacyRef<T> | undefined | null)[]
+ ): RefCallback<T> =>
+ (value) => {
+ refs.forEach((ref) => {
+ if (typeof ref === 'function') {
+ ref(value);
+ } else if (ref !== null) {
+ (ref as MutableRefObject<Nullable<T>>).current = value;
+ }
+ });
+ };