Flux
Flux

Reputation: 77

Create React Svg from an array of elements

Given an array representing the tags of an svg ,

(6) ["<svg id="Ebene_1" style={{"enableBackground":"new …rg/2000/svg" x="0px" y="0px" xmlSpace="preserve">", "<g>", "<polygon style={{"fillRule":"evenodd","clipRule":"…9,12 24,12 24,15 19,15 19,18 14,18 14,21 &#x9;"/>", "<path d="M3.4,20.5c-0.1,0-0.3-0.1-0.4-0.2c-0.1-0.2…,0.4h-3.3L3.7,20.4C3.6,20.5,3.5,20.5,3.4,20.5z"/>", "</g>", "</svg>"]
0: "<svg id="Ebene_1" style={{"enableBackground":"new 0 0 32 32"}} version="1.1" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" xmlSpace="preserve">"
1: "<g>"
2: "<polygon style={{"fillRule":"evenodd","clipRule":"evenodd"}} points="9,21 9,24 4,24 4,27 8.5,27 9.4,27 13.7,27 18.8,27 23.9,27 29,27 &#xD;&#xA;&#x9;&#x9;29,12 24,12 24,15 19,15 19,18 14,18 14,21 &#x9;"/>"
3: "<path d="M3.4,20.5c-0.1,0-0.3-0.1-0.4-0.2c-0.1-0.2-0.1-0.5,0.1-0.6L24.5,5.2c0.1,0,0.2-0.1,0.2-0.1h3.4c0.2,0,0.4,0.2,0.4,0.4&#xD;&#xA;&#x9;&#x9;c0,0.2-0.2,0.4-0.4,0.4h-3.3L3.7,20.4C3.6,20.5,3.5,20.5,3.4,20.5z"/>"
4: "</g>"
5: "</svg>"
length: 6
__proto__: Array(0)
how do I go about recreating the svg in react. It has to be done on the fly as the image given to me is a users choice, and as such I cannot just replicate each array item in react and pass in the props.

Upvotes: 1

Views: 746

Answers (2)

benchpresser
benchpresser

Reputation: 2188

Not the best method, but you can use <div dangerouslySetInnerHTML={{__html:yoursvgdata }} />

Upvotes: 0

Fernando Colom
Fernando Colom

Reputation: 377

you can use svg-inline-loader with webpack.

Add the loader in webpack config

    {
        test: /\.svg$/,
        loader: 'svg-inline-loader',
    },

Install svg-inline-react from npm

You can import a svg like this:

const icon = require('svg/icon.svg');

And you can use like this:

import InlineSVG from 'svg-inline-react';

<InlineSVG src={require("svg-inline-loader!icon.svg")} />

Upvotes: 3

Related Questions