Skip to content

Commit

Permalink
Add more parameters to useForkRef
Browse files Browse the repository at this point in the history
  • Loading branch information
michaldudak committed Sep 8, 2021
1 parent de3d15a commit 2812477
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions packages/mui-utils/src/useForkRef.ts
Expand Up @@ -2,22 +2,26 @@ import * as React from 'react';
import setRef from './setRef';

export default function useForkRef<Instance>(
...refs: Array<React.Ref<Instance> | null | undefined>
refA: React.Ref<Instance> | null | undefined,
refB: React.Ref<Instance> | null | undefined,
refC?: React.Ref<Instance> | null | undefined,
refD?: React.Ref<Instance> | null | undefined,
): React.Ref<Instance> | null {
/**
* This will create a new function if the ref props change and are defined.
* This means react will call the old forkRef with `null` and the new forkRef
* with the ref. Cleanup naturally emerges from this behavior.
*/
return React.useMemo(() => {
if (refs.every((ref) => ref == null)) {
if (refA == null && refB == null && refC == null && refD == null) {
return null;
}

return (refValue) => {
refs.forEach((ref) => {
setRef(ref, refValue);
});
setRef(refA, refValue);
setRef(refB, refValue);
setRef(refC, refValue);
setRef(refD, refValue);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...refs]);
}, [refA, refB, refC, refD]);
}

0 comments on commit 2812477

Please sign in to comment.