Parse SVG file to React component

大兔子大兔子 提交于 2021-01-29 12:39:12

问题


I have an SVG file: check.svg

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.3 28.3"><path d="M25.2 3.638l-1.6 1.6c-4.3 4.3-8.9 9.2-13.2 13.6l-5.9-4.9-1.7-1.4-2.8 3.3 1.7 1.4 7.5 6.2 1.6 1.3 1.4-1.4c4.8-4.8 9.9-10.4 14.6-15l1.6-1.6-3.2-3.1z"/></svg>

I want a React component from it; but I don't want any wrapper tag, just

<svg>
    <path […]/>
</svg>

I know I can do something like

const renderSvg = svg => React.createElement('svg', {
  dangerouslySetInnerHTML: { __html: svg }
});

or even easier

const RenderSvg = (svg) => <svg dangerouslySetInnerHTML={{ __html: svg }} />;

But I would end up with:

<svg>
  <svg>
    <path […]/>
  </svg>
</svg>

Does anyone know how to achieve this without using an external library?


回答1:


Have your SVG in a separate file, than import that as a component, like this:

import {ReactComponent as Circle} from "./circle.svg"

Following is a demo sandbox



来源:https://stackoverflow.com/questions/60455670/parse-svg-file-to-react-component

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