Update mergeRefs util for React 19 (#11108)
This commit is contained in:
@@ -984,11 +984,6 @@
|
|||||||
"count": 1
|
"count": 1
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"src/lib/merge-refs.ts": {
|
|
||||||
"@typescript-eslint/no-explicit-any": {
|
|
||||||
"count": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"src/lib/notifications/notifications.ts": {
|
"src/lib/notifications/notifications.ts": {
|
||||||
"@typescript-eslint/no-floating-promises": {
|
"@typescript-eslint/no-floating-promises": {
|
||||||
"count": 5
|
"count": 5
|
||||||
|
|||||||
+32
-11
@@ -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.
|
* 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
|
* 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 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.
|
* returns a ref callback function that can be used to merge multiple refs into a single ref.
|
||||||
*/
|
*/
|
||||||
export function mergeRefs<T = any>(
|
export function mergeRefs<T>(refs: (Ref<T> | undefined)[]): Ref<T> {
|
||||||
refs: Array<React.MutableRefObject<T> | React.Ref<T> | undefined>,
|
return (value: T | null) => {
|
||||||
): React.RefCallback<T> {
|
const cleanups: (() => void)[] = []
|
||||||
return value => {
|
|
||||||
refs.forEach(ref => {
|
for (const ref of refs) {
|
||||||
if (typeof ref === 'function') {
|
const cleanup = assignRef(ref, value)
|
||||||
ref(value)
|
const isCleanup = typeof cleanup === 'function'
|
||||||
} else if (ref != null) {
|
cleanups.push(isCleanup ? cleanup : () => assignRef(ref, null))
|
||||||
;(ref as React.MutableRefObject<T | null>).current = value
|
}
|
||||||
}
|
|
||||||
})
|
return () => {
|
||||||
|
for (const cleanup of cleanups) cleanup()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user