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

19,051

Solution 1

<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>

Solution 2

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.

Share:
19,051
johnnyshrewd
Author by

johnnyshrewd

I like pizza and dogs.

Updated on July 18, 2022

Comments

  • johnnyshrewd
    johnnyshrewd almost 2 years

    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

  • aldel
    aldel over 4 years
    I had trouble getting this to work in the current version of antd (3.23.1). See my answer for the way I solved it.
  • Adam Cox
    Adam Cox over 4 years
    Were you able to extend custom icon use within the route/menu in config.ts ?