Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly render JSX.Element or React.ReactNode type while mapping over array of objects in React?

I have this sidebar data

export const adminSidebarData: SidebarProps["sidebarData"] = [
  {
    title: "Dashboard",
    link: "/admin/dashboard",
    IconComponent: <IconDashboard className="icon" />,
  },
  {
    title: "Users",
    link: "/admin/dashboard/users",
    IconComponent: <IconDashboard />,
  }
];

My typescript type for sidebarData is

sidebarData: {
    title: string;
    link: string;
    IconComponent: JSX.Element;
  }[];

And I am rendering the data in UI like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{sidebarData.map((data) => {
          return (
            <Link href={data.link} className="w-full" key={data.link}>
              <div
                key={data.link}
                className="mx-2 flex w-full bg-white px-2 py-2"
              >
                {data.IconComponent}
                <p className="">{data.title}</p>
              </div>
            </Link>
          );
        })}

As you can see, I am rendering the icon like {data.IconComponent} I cannot pass dynamic props to component this way

But I wanted to render the component as <data.IconComponent/> or <IconComponent/> so that I will be able to pass props dynamically. Maybe changing the color based on the current route.
What change should I make to achieve this? Thank you.

>Solution :

you can do it this way

type SidebarItem = {
  title: string;
  link: string;
  IconComponent: React.ComponentType<{ className?: string }>;
};
type SidebarProps = {
  sidebarData: SidebarItem[];
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading