首页 > 解决方案 > Parse SVG file to React component

问题描述

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?

标签: javascriptreactjssvg

解决方案


将 SVG 放在单独的文件中,而不是将其作为组件导入,如下所示:

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

以下是一个演示沙箱


推荐阅读