Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a component as a prop using Next 13

I have a client component called Tab:

import * as React from "react";
import type { IconType } from "react-icons";

type TabProps = {
  Icon: IconType;
  label: string;
  isActive?: boolean;
};


export default function Tab({
  Icon,
  label,
  isActive = false,
  ...props
}: TabProps) {
  return (
    <div>
      <Icon size={20} />
      {label}
    </div>
  );
}

Whenever I try to use this component, I get this error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".

Ok. I have tried wrapping the component passed via Icon in a function that makes use of "use server" but Next is asking me to enable some experimental flag to make use of the directive.

Is there some way to achieve what I want without going through all of this? I know this was possible in old react. Do I need to declare the Icons as client components prior to using them or is there a better solution?

like image 747
Dowen Robinson Avatar asked Sep 18 '25 20:09

Dowen Robinson


1 Answers

You can't pass a component from server component to a client component, as it needs to be serializable.

But you can use Slot approach. In your Tab.tsx:

import React from "react";

type TabProps = {
  Icon: React.ReactElement;
  label: string;
  isActive?: boolean;
};


export default function Tab({
  Icon,
  label,
  isActive = false,
  ...props
}: TabProps) {
  return (
    <div>
      <Icon.type {...Icon.props} size={20}/>
      {label}
    </div>
  );
}

Your parent component:

<Tab Icon={<Icon/>}/>
like image 100
Gasanov Avatar answered Sep 21 '25 11:09

Gasanov