Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
SVG2JSX – Convert SVG to Valid React SVG (svg2jsx.herokuapp.com)
61 points by balajmarius on May 3, 2017 | hide | past | favorite | 28 comments


The site would be much better if it loaded a sample SVG by default so I don't have to hunt down the source for an SVG that I have lying around (or on the internet).


To save you guys a few clicks:

    <svg viewBox="0 0 104 97" xmlns="http://www.w3.org/2000/svg">
        <path d="M14,85l3,9h72c0,0,5-9,4-10c-2-2-79,0-79,1" fill="#7C4E32"/>
        <path d="M19,47c0,0-9,7-13,14c-5,6,3,7,3,7l1,14c0,0,10,8,23,8c14,0,26,1,28,0c2-1,9-2,9-4c1-1,27,1,27-9c0-10,7-20-11-29c-17-9-67-1-67-1" fill="#E30000"/>
        <path d="M17,32c-3,48,80,43,71-3 l-35-15" fill="#FFE1C4"/>
        <path d="M17,32c9-36,61-32,71-3c-20-9-40-9-71,3" fill="#8ED8F8"/>
        <path d="M54,35a10 8 60 1 1 0,0.1zM37,38a10 8 -60 1 1 0,0.1z" fill="#FFF"/>
        <path d="M41,6c1-1,4-3,8-3c3-0,9-1,14,3l-1,2h-2h-2c0,0-3,1-5,0c-2-1-1-1-1-1l-3,1l-2-1h-1c0,0-1,2-3,2c0,0-2-1-2-3M17,34l0-2c0,0,35-20,71-3v2c0,0-35-17-71,3M5,62c3-2,5-2,8,0c3,2,13,6,8,11c-2,2-6,0-8,0c-1,1-4,2-6,1c-4-3-6-8-2-12M99,59c0,0-9-2-11,4l-3,5c0,1-2,3,3,3c5,0,5,2,7,2c3,0,7-1,7-4c0-4-1-11-3-10" fill="#FFF200"/>
        <path d="M56,78v1M55,69v1M55,87v1" stroke="#000" stroke-linecap="round"/>
        <path d="M60,36a1 1 0 1 1 0-0.1M49,36a1 1 0 1 1 0-0.1M57,55a2 3 0 1 1 0-0.1M12,94c0,0,20-4,42,0c0,0,27-4,39,0z"/>
        <path d="M50,59c0,0,4,3,10,0M56,66l2,12l-2,12M25,50c0,0,10,12,23,12c13,0,24,0,35-15" fill="none" stroke="#000" stroke-width="0.5"/>
    </svg>


It is on my TODO list, probably will release tomorrow.


You could consider linking this up with open clip art.


it's done!


React is such a nice way to make SVGs generally. My team was building a microservices to generate our dynamic images, then had the realization: our frontend is React, and we can make these images client-side as inline SVGs (or server side if we need using the same code).

There's some browser compatibility issues we have to stay on top of, but overall it's been a blast.


I just started doing this for a project at work. It works amazingly well. I ended building a react designer to handle loading and creating new elements so that we can create images on the web versus converting an existing SVG from an illistrator file.


For anyone who looked at the repository linked from the Heroku app and was confused as to how this works (or indeed the extent of what it does), the actual transformation is being done server-side, using this: https://github.com/balajmarius/svg-to-jsx/blob/master/index.... (from the same author).


Related: Babel transform to load SVGs as React components: https://github.com/jhamlet/svg-react-loader


Upvoted, but it's actually a webpack loader not a babel transform.


I'm curious: what's the main use-case for this functionality?

Particularly given it's a lossy transformation, I can't think of any situation where I'd use this.


It seems useful if you have an SVG that has been produced in a vector graphics editor that you want in a JSX format to make pieces interactive using React.


seems to just change double quotes to single. find and replace. I don't notice any other difference.

oh, noticed `0.5` turn into `.5` and `black` turn into `#000`. not sure how that will make it more JSX compatible


>oh, noticed `0.5` turn into `.5` and `black` turn into `#000`. not sure how that will make it more JSX compatible

That's for minimizing code size. In both of your examples one byte is shaved off.

Arguably this is a case of premature optimization though. For production, the Closure compiler will do a far better job at it. For development, you won't notice the difference of shaving off a few kilobytes.


hey lucideer, I think it's usefull when you had to work with SVG sprites + React.

Converts the attributes not supported in React (xlink:href, fill-rule, etc.) to valid React attributes and also in case you have inline styles (eg. style="margin-left:20px") this tool will generate a Javascript object from that style ({marginLeft: 20}), which is valid React inline style.

Also, I think it's super usefull in case you had to use an inline SVG exported from Sketch or AI


I quickly tested it before commenting above and it stripped and discarded quite a lot of my SVG code (hence my comment on lossy transformations). I've just looked into React's SVG support and it is poor and hacky (e.g. it hardcodes two ns prefixes rather than supporting aliased uris as per the SVG​ spec.), so I guess my main objection should really be with React's (lack of) decent SVG support rather than with this tool.

That said though, I've used SVG in React quite a lot myself, but I've always opted for SVG as strings or external static resources rather than inlined vdom objects - this has worked fine for me as I would think of SVG as a display format so it has never needed granular access according to application state in my experience.


Super useful if you need to inline some SVG in a react app. I recently learned about the benefits of inline SVG thanks to front-end center and started using similar to OP's tool for that.


React supports these SVG attributes:

https://facebook.github.io/react/docs/dom-elements.html#all-...

    accentHeight accumulate additive alignmentBaseline allowReorder alphabetic 
    amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
    baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
    clip clipPath clipPathUnits clipRule colorInterpolation
    colorInterpolationFilters colorProfile colorRendering contentScriptType
    contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
    display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
    end exponent externalResourcesRequired fill fillOpacity fillRule filter
    filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
    fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
    g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
    gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
    imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
    kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
    limitingConeAngle local markerEnd markerHeight markerMid markerStart
    markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
    numOctaves offset opacity operator order orient orientation origin overflow
    overlinePosition overlineThickness paintOrder panose1 pathLength
    patternContentUnits patternTransform patternUnits pointerEvents points
    pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
    r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
    requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
    spacing specularConstant specularExponent speed spreadMethod startOffset
    stdDeviation stemh stemv stitchTiles stopColor stopOpacity
    strikethroughPosition strikethroughThickness string stroke strokeDasharray
    strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
    strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
    textDecoration textLength textRendering to transform u1 u2 underlinePosition
    underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
    vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
    vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
    writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
    xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlns xmlnsXlink xmlBase
    xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan
Anything else needs to be stripped out - mostly stuff like meta data with ":" in the tag.


I have not yet tried this OP's tool, but I've been using something similar (http://svg-jsx.patmoody.com/) and I'm very happy with the utility. Next time I need to inline SVG in react I will use this one.


Slight aside: what are the performance impacts here? I've been wondering for a while whether JSX is a little dangerous in that it makes repeated, huge, nested calls to React.createElement() look like plaintext.

For example, I could easily just run element.innerHTML = "<svg...>" to add SVG content to my page. If the SVG isn't being dynamically updated, doesn't making JSX like this incur a large and unnecessary overhead?


Does anyone know why the page try to load the url "https://localhost:9000/sockjs-node/info?t=1493857220633" ?


Probably some sort of live reload functionality for development


fixed


Is `xmlns` actually required? We've pulled it out of all of our React svg's and everything seems to work fine. Does anyone know of any quirks this could be causing?


It depends, if you're delivering stand alone SVGs (as opposed to inlined in some html) then browsers may not render the graphic properly without it.


check out https://www.npmjs.com/package/react-icon-loader - converts svg to stateless component with svgo optimizations


I thought parens around any SVG would make it valid JSX.


You have to escape some portions, like CSS, (otherwise { and } will be interpreted as JS expression interpolation) remove xml namespaces, `class` also needs to be renamed to `className`, among other tweaks.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: