Rendering Material-UI icons from an array

xabra

Background info:
I'm using react and material-ui.
To keep the code clean, I populate menu items from a const array, like so:

const menuItems = [
  { label: "Home", path: "/home" },
  { label: "Accounts", path: "/accounts" },
  { label: "Organizations", path: "/organizations" },
];

Each item in the array is an object containing a label and a redirect path. I map over the items when rendering. Very basic.

Problem:
I would like to include a material-ui icon component in the menuItems array so the icon can be rendered next to the label. But I can't find a way to reference the icons by a name string
https://material-ui.com/components/material-icons/

Possible solutions:

  1. put the icon component into a string: { label: "Accounts", path: "/accounts" }, icon: "<AccountBox/>"} but then I somehow need to evaluate the string into jsx. I don't know how.

  2. Make a react functional component which renders a different icon depending on a prop, for example: <IconSwitch icon = {"accountIcon"} /> and hard-code different icons inside the RFC. Not pretty, but should work.

  3. Punt and use different icons such as svg icons or font icons that can referenced by a name string.

Any suggestions on how to do this? Thanks

Zachary Haber

You can use the Icon component. https://material-ui.com/components/icons/#icon-font-icons

To use an icon simply wrap the icon name (font ligature) with the Icon component, for example:

import Icon from '@material-ui/core/Icon';

<Icon>star</Icon>

https://codesandbox.io/s/material-demo-forked-sj66h?file=/demo.tsx

Assuming you set up your menu items with the appropriate icon ligatures:

  const menuItems = [
    { label: "Home", path: "/home", icon: "home" },
    { label: "Accounts", path: "/accounts", icon: "account_circle" },
    { label: "Organizations", path: "/organizations", icon: "settings" }
  ];

Then you can map over them:

      {menuItems.map(({ label, icon }) => {
        return (
          <span key={label}>
            {label} <Icon>{icon}</Icon>
          </span>
        );
      })}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related