Reputation: 15
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?
Upvotes: 0
Views: 2170
Reputation: 335
The method mencioned by @Mohammad Faisal works just fine, thank you!
Just updating for antd
version >= v4.x.x
As we can see in the docs: https://ant.design/components/icon/#Custom-SVG-Icon
import Icon, { OtherIconsYouNeed } from '@ant-design/icons';
import MyObject from "../path/to/object.ts"
export default function MyComponent() {
return (
<Icon component={MyObject.someField} />
)
}
Upvotes: 0
Reputation: 2421
On antd 4.x.x without using antd-compatible, you can do
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 />,
},
];
instead of string.
Upvotes: 0
Reputation: 2363
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>
Upvotes: 2