How to import svg into antd -> Icon component

♀尐吖头ヾ 提交于 2019-12-23 17:41:54

问题


Hey I am trying to import my own svg into antd -> Icon component like in the documentation but i got an exception

InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/archive-solid.3c305173.svg') is not a valid name.

Im using create react app 2.1.1 and antd version 3.10.3 I would not want to do the create react app eject and i dont access to webpack any ideas. that the code:

import React, { Component } from "react";
import { Layout, Menu, Icon } from "antd";
import ArchiveSVG from "../../../img/icons/archive-solid.svg";

const { Sider } = Layout;

class SideBar extends Component {
state = {
  collapsed: false
};

onCollapse = collapsed => {
  this.setState({ collapsed });
};

render() {
 return (
   <Sider
     collapsible
     collapsed={this.state.collapsed}
     onCollapse={this.onCollapse}
   >
     <div className={styles.logo} />
     <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
       <Menu.Item key="4">
         <Icon component={ArchiveSVG} />
         <span>Products</span>
       </Menu.Item>
     </Menu>
   </Sider>
 );
}
}

回答1:


Simplify your svg and export is as JSX like following

import React from 'react';

export default () => <svg viewBox="0 0 512 512" width="1em" height="1em" fill="currentColor">
    <path fill="currentColor" d="M8.309 189.836L184.313 37.851C199.719 24.546 224 35.347 224 56.015v80.053c160.629 1.839 288 34.032 288 186.258 0 61.441-39.581 122.309-83.333 154.132-13.653 9.931-33.111-2.533-28.077-18.631 45.344-145.012-21.507-183.51-176.59-185.742V360c0 20.7-24.3 31.453-39.687 18.164l-176.004-152c-11.071-9.562-11.086-26.753 0-36.328z">
    </path>
</svg>

and then use is like

<Icon component={RepySVG} />

Please create a code pen for more help.




回答2:


You need to add the following lines to your webpack.config.js, so as to import SVG as a component directly.

            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: 'babel-loader',
                    },
                    {
                        loader: '@svgr/webpack',
                        options: {
                            babel: false,
                            icon: true,
                        },
                    },
                ],
            }

Related doc




回答3:


This method worked for me

import ArchiveSVG from "../../../img/icons/archive-solid.svg";

const archive = () => (
   <img src={ArchiveSVG} />
);

Then use like this

<Icon component={archive} />

Happy coding :-)



来源:https://stackoverflow.com/questions/53322676/how-to-import-svg-into-antd-icon-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!