From 2bad02cc57c226560dc6f1784ad454842c267bd4 Mon Sep 17 00:00:00 2001 From: cahnory Date: Thu, 19 Oct 2023 10:57:29 +0200 Subject: [PATCH 1/2] fix: typing of ButtonPrimitive ref - add forwardConditionalRefs utility function - add composeRefs utility function --- .../ButtonPrimitive/ButtonPrimitive.tsx | 28 ++++------- apps/react-sample/src/utils/composeRefs.ts | 18 +++++++ .../src/utils/forwardConditionalRefs.ts | 48 +++++++++++++++++++ 3 files changed, 74 insertions(+), 20 deletions(-) create mode 100644 apps/react-sample/src/utils/composeRefs.ts create mode 100644 apps/react-sample/src/utils/forwardConditionalRefs.ts diff --git a/apps/react-sample/src/components/primitives/ButtonPrimitive/ButtonPrimitive.tsx b/apps/react-sample/src/components/primitives/ButtonPrimitive/ButtonPrimitive.tsx index cac3cff..e4dbfcd 100644 --- a/apps/react-sample/src/components/primitives/ButtonPrimitive/ButtonPrimitive.tsx +++ b/apps/react-sample/src/components/primitives/ButtonPrimitive/ButtonPrimitive.tsx @@ -1,32 +1,20 @@ -import type { ComponentProps, ForwardedRef, ReactElement } from "react"; +import type { ComponentPropsWithoutRef } from "react"; -import { forwardRef } from "react"; +import { forwardConditionalRef } from "../../../utils/forwardConditionalRefs"; -type AnchorRef = ForwardedRef; -type ButtonRef = ForwardedRef; -type MixedRef = ForwardedRef; - -type AnchorProps = Omit, "ref"> & { +type AnchorProps = Omit, "href"> & { href: string; - ref?: AnchorRef | MixedRef | undefined; }; -type ButtonProps = Omit, "ref"> & { +type ButtonProps = ComponentPropsWithoutRef<"button"> & { href?: undefined; - ref?: ButtonRef | MixedRef | undefined; }; -type ButtonPrimitiveProps = AnchorProps | ButtonProps; - -export const ButtonPrimitive = forwardRef< - HTMLAnchorElement & HTMLButtonElement, - ButtonPrimitiveProps ->(function renderButtonPrimitive(props, ref) { +export const ButtonPrimitive = forwardConditionalRef< + [[HTMLAnchorElement, AnchorProps], [HTMLButtonElement, ButtonProps]] +>(function ButtonPrimitiveForwardedRef(props, ref) { return props.href === undefined ? (