ui icon indicating copy to clipboard operation
ui copied to clipboard

[bug]: NavigationMenuTrigger - Next.js: Error: React.Children.only expected to receive a single React element child

Open PaulSinghDev opened this issue 4 months ago • 0 comments

Describe the bug

When you use the asChild prop and pass your child to the <NavigationMenuTrigger /> component I am receiving the Next.js: Error: React.Children.only expected to receive a single React element child error even though I am only passing one child, for example, the following triggers the error (as you can see there is only one child):

      <NavigationMenuTrigger asChild>
        <Button variant="ghost" className="relative h-10 w-10 rounded-full">
          <Avatar className="h-10 w-10">
              <AvatarImage src={image} alt="Avatar" />
              <AvatarFallback>{initials ? initials : "U"}</AvatarFallback>
          </Avatar>
        </Button>
      </NavigationMenuTrigger>

I have checked the source of what is added when I run npx shadcn@latest navigation-menu and I have located the issue to be the fact that the current form of the element doesn't take take the asChild prop into account when rendering children, as you can see here:

  <NavigationMenuPrimitive.Trigger
    ref={ref}
    className={cn(navigationMenuTriggerStyle(), "group", className)}
    {...props}
  >
    {children}{" "}
    <ChevronDown
      className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
      aria-hidden="true"
    />
  </NavigationMenuPrimitive.Trigger>

I have fixed this by conditionally rendering the chevron icon as follows:

  <NavigationMenuPrimitive.Trigger
    ref={ref}
    className={cn(navigationMenuTriggerStyle(), "group", className)}
    {...props}
  >
    {!props.asChild ? (
      <>
        {children}{" "}
        <ChevronDown
          className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
          aria-hidden="true"
        />
      </>
    ) : (
      children
    )}
  </NavigationMenuPrimitive.Trigger>

Affected component/components

NavigationMenuTrigger

How to reproduce

  1. Setup a <NavigationMenuItem /> component
  2. Add a <NavigationMenuTrigger asChild> component
  3. Add a single child to the <NavigationMenuTrigger asChild> component (as above)

Codesandbox/StackBlitz link

No response

Logs

No response

System Info

Don't think this is relevant as the issue is pretty standard, I have a fix and will make a PR

Before submitting

  • [X] I've made research efforts and searched the documentation
  • [X] I've searched for existing issues

PaulSinghDev avatar Sep 27 '24 12:09 PaulSinghDev