From d9079dd526e6c6ba3a6157130a69dc59fa3646fc Mon Sep 17 00:00:00 2001 From: Sam Kvale Date: Thu, 28 Sep 2023 14:52:14 -0500 Subject: [PATCH] feat: allow a ref to be undefined in the types (#33) --- src/index.test.tsx | 22 ++++++++++++++++++++++ src/index.tsx | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/index.test.tsx b/src/index.test.tsx index 3844323..6686baa 100644 --- a/src/index.test.tsx +++ b/src/index.test.tsx @@ -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 ? ( + + ) : null; + }; + const { rerender } = render(); + expect(refAsFunc).toHaveBeenCalledTimes(1); + expect(refAsFunc).toHaveBeenCalledWith("refValue"); + expect(refAsObj.current).toBe("refValue"); + rerender(); + expect(refAsFunc).toHaveBeenCalledTimes(2); + expect(refAsFunc).toHaveBeenCalledWith(null); + expect(refAsObj.current).toBe(null); +}); diff --git a/src/index.tsx b/src/index.tsx index b2e688b..2ff12ff 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,7 +1,7 @@ import type * as React from "react"; export function mergeRefs( - refs: Array | React.LegacyRef> + refs: Array | React.LegacyRef | undefined | null> ): React.RefCallback { return (value) => { refs.forEach((ref) => {