Update mergeRefs util for React 19 (#11108)

This commit is contained in:
DS Boyce
2026-07-08 12:32:15 -07:00
committed by GitHub
parent 6dce96881c
commit 0a4f5e132c
2 changed files with 32 additions and 16 deletions
-5
View File
@@ -984,11 +984,6 @@
"count": 1
}
},
"src/lib/merge-refs.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 1
}
},
"src/lib/notifications/notifications.ts": {
"@typescript-eslint/no-floating-promises": {
"count": 5
+32 -11
View File
@@ -1,3 +1,22 @@
import {type Ref, type RefCallback} from 'react'
/**
* Assigns a value to a ref.
* @param ref The ref to assign the value to.
* @param value The value to assign to the ref.
* @returns The ref cleanup callback, if any.
*/
function assignRef<T>(
ref: Ref<T> | undefined | null,
value: T | null,
): ReturnType<RefCallback<T>> {
if (typeof ref === 'function') {
return ref(value)
} else if (ref) {
ref.current = value
}
}
/**
* 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
@@ -12,16 +31,18 @@
* @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.Ref<T> | undefined>,
): 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
}
})
export function mergeRefs<T>(refs: (Ref<T> | undefined)[]): Ref<T> {
return (value: T | null) => {
const cleanups: (() => void)[] = []
for (const ref of refs) {
const cleanup = assignRef(ref, value)
const isCleanup = typeof cleanup === 'function'
cleanups.push(isCleanup ? cleanup : () => assignRef(ref, null))
}
return () => {
for (const cleanup of cleanups) cleanup()
}
}
}