Kaynağa Gözat

fix: improve custom Button component (#28)

Update Button component to accept both `asChild` and
custom properties.
Sat Naing 1 yıl önce
ebeveyn
işleme
9ed0da4538
1 değiştirilmiş dosya ile 34 ekleme ve 23 silme
  1. 34 23
      src/components/custom/button.tsx

+ 34 - 23
src/components/custom/button.tsx

@@ -35,38 +35,49 @@ const buttonVariants = cva(
   }
 )
 
-export interface ButtonProps
+interface ButtonPropsBase
   extends React.ButtonHTMLAttributes<HTMLButtonElement>,
-    VariantProps<typeof buttonVariants> {
-  asChild?: boolean
-  loading?: boolean
-  leftSection?: JSX.Element
-  rightSection?: JSX.Element
-}
+    VariantProps<typeof buttonVariants> {}
 
-const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+type ButtonProps = ButtonPropsBase &
   (
-    {
-      className,
-      variant,
-      size,
-      asChild = false,
-      children,
-      disabled,
+    | { asChild: true }
+    | {
+        asChild?: false
+        loading?: boolean
+        leftSection?: JSX.Element
+        rightSection?: JSX.Element
+      }
+  )
+
+const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+  ({ className, variant, size, children, ...props }, ref) => {
+    if (props.asChild) {
+      return (
+        <Slot
+          className={cn(buttonVariants({ variant, size, className }))}
+          ref={ref}
+          {...props}
+        >
+          {children}
+        </Slot>
+      )
+    }
+
+    const {
       loading = false,
       leftSection,
       rightSection,
-      ...props
-    },
-    ref
-  ) => {
-    const Comp = asChild ? Slot : 'button'
+      disabled,
+      ...otherProps
+    } = props
+
     return (
-      <Comp
+      <button
         className={cn(buttonVariants({ variant, size, className }))}
         disabled={loading || disabled}
         ref={ref}
-        {...props}
+        {...otherProps}
       >
         {((leftSection && loading) ||
           (!leftSection && !rightSection && loading)) && (
@@ -78,7 +89,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
         {rightSection && loading && (
           <IconLoader2 className='ml-2 h-4 w-4 animate-spin' />
         )}
-      </Comp>
+      </button>
     )
   }
 )