Skip to content

Bug: Function Components Cannot Be Given Refs in Button Component #52

@DeveloperAmrit

Description

@DeveloperAmrit

Description
The Button component in the project throws a warning when used in certain contexts. The warning indicates that function components cannot be given refs, which occurs because the Button component is not wrapped in React.forwardRef.

How to Reproduce

  1. Go to transactions page
  2. Click fetch transactions
  3. Observe the error in the console.

Actual behaviour
Following error is displayed in console

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `SlotClone`. Error Component Stack
    at Button (button.tsx:41:3)
    at DashboardPageLayout (index.tsx:14:3)
    at TransactionsPage (page.tsx:43:102)
    at TooltipProvider (tooltip.tsx:9:3)
    at SidebarProvider (sidebar.tsx:46:3)
    at Providers (providers.tsx:9:29)
    at body (<anonymous>)
    at html (<anonymous>)
    at RootLayout [Server] (<anonymous>)

Screenshot

Image

Expected Behavior
The Button component should handle refs properly without throwing any warnings. It should be wrapped in React.forwardRef to allow refs to be passed down correctly.

Potential Fix
Wrap the Button component in React.forwardRef to handle refs. Here’s an example of the fix:

const Button = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<"button"> &
    VariantProps<typeof buttonVariants> & {
      asChild?: boolean;
    }
>(({ className, variant, size, asChild = false, ...props }, ref) => {
  const Comp = asChild ? Slot : "button";

  return (
    <Comp
      data-slot="button"
      className={cn(buttonVariants({ variant, size, className }))}
      ref={ref}
      {...props}
    />
  );
});
Button.displayName = "Button";

This fix ensures that the Button component can accept refs and resolves the warning.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions