[SOLVED] Render React Element within Array

Issue

I have an array of items, which are defined by a string and an icon component:

type MyItem = {
  Title: string;
  Icon: React.ElementType;
};

export const MyItems: MyItem[] = [
  { Title: "Inbox", Icon: InboxIcon },
  { Title: "Users", Icon: UserIcon },
  { Title: "Settings", Icon: SettingsIcon },
];

Now I want to display them within a component:

<>
    {MyItems.map((item, index) => (
      <h1>item.Title</h1>
      // render icon component here: item.Icon
    ))}
</>

How can I render the icon component (without changing the array structure)?

Solution

I’m guessing here that your icons are essentially React Components. If so then you can try out the code below:

<>
    {MyItems.map((item, index) => (
      <>
      <h1>item.Title</h1>
      {item.Icon}
      </>
    ))}
</>

Answered By – Abhik Banerjee

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *