乐闻世界logo
搜索文章和话题

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

1个答案

1

When using the ANTD design library, if you need to add custom images or icons to the menu component, you can follow these steps:

Step 1: Prepare Icons

First, ensure you have accessible icon files. These can be SVG, PNG, or other image formats. If you are using SVG icons, you can conveniently import and use them with libraries like react-icons.

Step 2: Import Icons into Your Component

If your icon is an SVG file, you can directly import it in your React component. For example:

javascript
import { ReactComponent as YourIcon } from './path_to_your_icon.svg';

For other image types, you can directly use them in the img tag:

javascript
import yourIcon from './path_to_your_icon.png';

Step 3: Add Icons Using <Menu.Item>

In the ANTD <Menu> component, you can add icons to <Menu.Item> using the icon prop. For example:

jsx
import { Menu } from 'antd'; import { IconName } from '@ant-design/icons'; // If using ANTD built-in icons import { ReactComponent as YourCustomIcon } from './path_to_your_custom_icon.svg'; // Custom SVG icon const MyMenu = () => { return ( <Menu> <Menu.Item key="1" icon={<YourCustomIcon style={{ fontSize: '16px' }} />}> Menu Item 1 </Menu.Item> <Menu.Item key="2" icon={<img src={yourIcon} style={{ width: '16px', height: '16px' }} alt="icon" />}> Menu Item 2 </Menu.Item> </Menu> ); };

Example Explanation

In the above code:

  • For SVG icons, I used a React component <YourCustomIcon /> and applied styles to adjust the icon size.
  • For PNG icons, I used the <img> tag and set the width and height via styles.

Notes

  • When adjusting icon size and color, ensure you use appropriate CSS styles.
  • Verify that icon file paths are correct and can be properly processed by Webpack or other module bundlers you are using.

By following this approach, you can flexibly integrate various custom icons into the ANTD menu component, enhancing both visual appeal and user experience.

2024年8月9日 20:42 回复

你的答案