Search code examples
arraysreactjstypescriptcomponents

Render React Element within Array


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}
          </>
        ))}
    </>