简体   繁体   中英

React use SVGR with svg in public folder

Is there any way I can import an SVG file in my public folder as a React component like so:

import { ReactComponent as MySvg } from '/assets/svg/mysvg.svg';

const MyComponent = () => {
  return (
    <div>
      <MySvg />
    </div>
  );
};

export default MyComponent;

I know there are workarounds like using an img tag but I really need my SVG to be used as a React component...

Thanks in advance !

you can use a loader in webpack, like this:

{
    test: /\.(svg)$/i, 
    loader: 'file-loader',
    options: {
      name: '/public/assets/svg/[name].[ext]'
    }
}

then, you can import your svg like this:

import MySvg from '/assets/svg/mysvg.svg';

const MyComponent = () => {
  return (
    <div>
      <MySvg width={36} height={36} />
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM