Skip to content

Commit d9079dd

Browse files
authored
feat: allow a ref to be undefined in the types (#33)
1 parent 93bec3a commit d9079dd

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/index.test.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,25 @@ test("mergeRefs", () => {
2121
expect(refAsFunc).toHaveBeenCalledWith(null);
2222
expect(refAsObj.current).toBe(null);
2323
});
24+
25+
test("mergeRefs with undefined and null refs", () => {
26+
const Dummy = React.forwardRef(function Dummy(_, ref) {
27+
React.useImperativeHandle(ref, () => "refValue");
28+
return null;
29+
});
30+
const refAsFunc = jest.fn();
31+
const refAsObj = { current: undefined };
32+
const Example: React.FC<{ visible: boolean }> = ({ visible }) => {
33+
return visible ? (
34+
<Dummy ref={mergeRefs([null, undefined, refAsFunc, refAsObj])} />
35+
) : null;
36+
};
37+
const { rerender } = render(<Example visible />);
38+
expect(refAsFunc).toHaveBeenCalledTimes(1);
39+
expect(refAsFunc).toHaveBeenCalledWith("refValue");
40+
expect(refAsObj.current).toBe("refValue");
41+
rerender(<Example visible={false} />);
42+
expect(refAsFunc).toHaveBeenCalledTimes(2);
43+
expect(refAsFunc).toHaveBeenCalledWith(null);
44+
expect(refAsObj.current).toBe(null);
45+
});

src/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type * as React from "react";
22

33
export function mergeRefs<T = any>(
4-
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>
4+
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T> | undefined | null>
55
): React.RefCallback<T> {
66
return (value) => {
77
refs.forEach((ref) => {

0 commit comments

Comments
 (0)