2023-02-15 16:20:58 -05:00
|
|
|
/*
|
2024-09-06 10:22:13 +02:00
|
|
|
Copyright 2023, 2024 New Vector Ltd.
|
2023-02-15 16:20:58 -05:00
|
|
|
|
2025-02-18 17:59:58 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
2024-09-06 10:22:13 +02:00
|
|
|
Please see LICENSE in the repository root for full details.
|
2023-02-15 16:20:58 -05:00
|
|
|
*/
|
|
|
|
|
|
2025-06-23 22:48:37 -04:00
|
|
|
import { type RefCallback, type RefObject, useCallback } from "react";
|
2023-02-01 11:32:10 -05:00
|
|
|
|
2023-02-13 22:38:27 -05:00
|
|
|
/**
|
|
|
|
|
* Combines multiple refs into one, useful for attaching multiple refs to the
|
|
|
|
|
* same DOM node.
|
|
|
|
|
*/
|
2023-02-01 11:32:10 -05:00
|
|
|
export const useMergedRefs = <T>(
|
2025-06-23 22:48:37 -04:00
|
|
|
...refs: (RefObject<T | null> | RefCallback<T | null> | null | undefined)[]
|
2023-02-01 11:32:10 -05:00
|
|
|
): RefCallback<T | null> =>
|
|
|
|
|
useCallback(
|
|
|
|
|
(value) =>
|
|
|
|
|
refs.forEach((ref) => {
|
|
|
|
|
if (typeof ref === "function") {
|
|
|
|
|
ref(value);
|
2025-06-24 08:28:00 -04:00
|
|
|
} else if (ref) {
|
2023-02-01 11:32:10 -05:00
|
|
|
ref.current = value;
|
|
|
|
|
}
|
|
|
|
|
}),
|
2023-02-13 21:57:57 -05:00
|
|
|
// Since this isn't an array literal, we can't use the static dependency
|
|
|
|
|
// checker, but that's okay
|
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
2023-10-11 10:42:04 -04:00
|
|
|
refs,
|
2023-02-01 11:32:10 -05:00
|
|
|
);
|