Update mergeRefs util for React 19 (#11108)
This commit is contained in:
@@ -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
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user