aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/helpers/refs.ts
blob: 74a695a6a04e7890640ab49b457307bd362cc3cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
      }
    });
  };