johnnyshrewd
johnnyshrewd

Reputation: 1180

How to add a custom image/icon in ANTD Design menu?

Using this example: https://ant.design/components/layout/#components-layout-demo-side

How can I add a custom image or icon instead of the default icons.

I tried:

<Menu.Item to="/" key="2">
  <img className="ant-menu-item" src={require('image.png')} />
  <span>Shopify</span>
  <Link to="/shopify">Home</Link>
</Menu.Item>

But that does not look good or does not respect the collapsed behaviour

Upvotes: 12

Views: 37080

Answers (5)

Regis
Regis

Reputation: 176

A bit of an old question, but I thought I'd post another solution here for those not wanting to go the webpack route like the docs recommend. You can simply create your own SVG component and then pass it to the antd icon component.

Something like this

// Icons.tsx
export const MyIcon = () => {
  return (
    <svg>
       // svg path data
    </svg>
  );
};

Then

// app.tsx
import Icon from "@ant-design/icons";
import { MyIcon } from "./Icons";

const App = () => {
    return (
        <Icon component={MyIcon} />
    )
}

I fiddled with this a little bit in a sandbox, and it seems to work just fine. I was using antd 4.23.3 for reference. Didn't test it a huge amount so there might be some style adjusting needed, not sure.

Upvotes: 2

Thinh Trann
Thinh Trann

Reputation: 1

icon:<img src="/static/icons/BH_tainan.svg"  height={20} style={{margin:"0 12px 0 0" ,paddingTop:10 ,float:"left"}}/>,

need float:"left" in your style

Upvotes: 0

aldel
aldel

Reputation: 6758

I tried several different ways of creating custom icons, and the one that was easiest and worked best was to use the component property of the antd Icon component. Just give it a functional component that returns whatever image you want to use:

<Icon component={() => (<img src="/image.svg" />)} />

This seems to work well within menu items and submenus, except that the icons don't line up perfectly with the menu text like the built-in icons do. I ended up adding transform: translateY(-3px) to the CSS to compensate for this (might depend on the image you use).

On the other hand, the official solution (for SVG images only) is to use the @svgr/webpack plugin to turn the SVG file into a component. This may have some advantages as far as layout and coloring (antd icons seem to prefer actual <svg> elements over <img> elements with SVG image files). But I'm not sure because I didn't go to the trouble of setting it up.

Upvotes: 16

Abhijit
Abhijit

Reputation: 941

<Menu.Item to="/" key="2">
    <img className="ant-menu-item" src=="{{ "image.png" | asset_url }}"/>
    <span>Shopify</span>
    <Link to="/shopify">Home</Link>
</Menu.Item>

Upvotes: 6

jayanes
jayanes

Reputation: 634

I hope this might be work. you need handle separate css file and put it this code

.ant-menu-item{background-image: url("theme5.jpg");}

Upvotes: 0

Related Questions