mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-29 03:45:15 +00:00
40 lines
939 B
JavaScript
40 lines
939 B
JavaScript
|
import { useMemo } from 'react';
|
||
|
|
||
|
var toFnRef = function toFnRef(ref) {
|
||
|
return !ref || typeof ref === 'function' ? ref : function (value) {
|
||
|
ref.current = value;
|
||
|
};
|
||
|
};
|
||
|
|
||
|
export function mergeRefs(refA, refB) {
|
||
|
var a = toFnRef(refA);
|
||
|
var b = toFnRef(refB);
|
||
|
return function (value) {
|
||
|
if (a) a(value);
|
||
|
if (b) b(value);
|
||
|
};
|
||
|
}
|
||
|
/**
|
||
|
* Create and returns a single callback ref composed from two other Refs.
|
||
|
*
|
||
|
* ```tsx
|
||
|
* const Button = React.forwardRef((props, ref) => {
|
||
|
* const [element, attachRef] = useCallbackRef<HTMLButtonElement>();
|
||
|
* const mergedRef = useMergedRefs(ref, attachRef);
|
||
|
*
|
||
|
* return <button ref={mergedRef} {...props}/>
|
||
|
* })
|
||
|
* ```
|
||
|
*
|
||
|
* @param refA A Callback or mutable Ref
|
||
|
* @param refB A Callback or mutable Ref
|
||
|
* @category refs
|
||
|
*/
|
||
|
|
||
|
function useMergedRefs(refA, refB) {
|
||
|
return useMemo(function () {
|
||
|
return mergeRefs(refA, refB);
|
||
|
}, [refA, refB]);
|
||
|
}
|
||
|
|
||
|
export default useMergedRefs;
|