Skip to content

Commit

Permalink
feat: allow a ref to be undefined in the types (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
skvale authored Sep 28, 2023
1 parent 93bec3a commit d9079dd
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,25 @@ test("mergeRefs", () => {
expect(refAsFunc).toHaveBeenCalledWith(null);
expect(refAsObj.current).toBe(null);
});

test("mergeRefs with undefined and null refs", () => {
const Dummy = React.forwardRef(function Dummy(_, ref) {
React.useImperativeHandle(ref, () => "refValue");
return null;
});
const refAsFunc = jest.fn();
const refAsObj = { current: undefined };
const Example: React.FC<{ visible: boolean }> = ({ visible }) => {
return visible ? (
<Dummy ref={mergeRefs([null, undefined, refAsFunc, refAsObj])} />
) : null;
};
const { rerender } = render(<Example visible />);
expect(refAsFunc).toHaveBeenCalledTimes(1);
expect(refAsFunc).toHaveBeenCalledWith("refValue");
expect(refAsObj.current).toBe("refValue");
rerender(<Example visible={false} />);
expect(refAsFunc).toHaveBeenCalledTimes(2);
expect(refAsFunc).toHaveBeenCalledWith(null);
expect(refAsObj.current).toBe(null);
});
2 changes: 1 addition & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type * as React from "react";

export function mergeRefs<T = any>(
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T> | undefined | null>
): React.RefCallback<T> {
return (value) => {
refs.forEach((ref) => {
Expand Down

0 comments on commit d9079dd

Please sign in to comment.