Search code examples
javascriptreactjsantd

How do I render an Ant Design Icon from a predefined Object


I have a file that lists menu items as shown

import React from "react";
import { Link, useRouteMatch } from "react-router-dom";
import {
  HomeOutlined,
  ProjectOutlined,
  DatabaseOutlined,
  RocketOutlined,
  SettingOutlined,
  FormatPainterOutlined,
} from "@ant-design/icons";

import { Menu } from "antd";

const { SubMenu } = Menu;

const stripTrailingSlash = (str) => {
  if (str.substr(-1) === "/") {
    return str.substr(0, str.length - 1);
  }
  return str;
};
export default React.memo(function SiderMenu({ singleOption, ...rest }) {
  let match = useRouteMatch();

  const { key, label, leftIcon, children } = singleOption;


  const url = stripTrailingSlash(match.url);


  return (
    <Menu.Item key={key} {...rest} icon={leftIcon}>
      <Link to={`${url}/${key}`}>{label}</Link>
    </Menu.Item>
  );
});

The singleOption prop file is shown below

const options = [
  {
    key: "home",
    label: "Home",
    leftIcon: "HomeOutlined",
  },
  {
    key: "project",
    label: "Projects",
    leftIcon: "ProjectOutlined",
  },
  {
    key: "data",
    label: "My Data",
    leftIcon: "DatabaseOutlined",
  },
  {
    key: "finished",
    label: "Compiled Data",
    leftIcon: "RocketOutlined",
  },
  {
    key: "settings",
    label: "Settings",
    leftIcon: "SettingsOutlined",
  },

I am trying to display an Ant Design Icon in the Menu.Item icon={leftIcons} from the Object but it shows up as plain text. Is there a way to render an icon from the object?


Solution

  • the prop icon expects a react object not a string value . what you can do is render your icons like this

    import { Icon} from 'antd';
    
    
    <Menu.Item key={key} {...rest} icon={<Icon type={leftIcon} />}>
          <Link to={`${url}/${key}`}>{label}</Link>
    </Menu.Item>