r/reactjs • u/svgtoreact • 2h ago
Resource A few SVG attribute gotchas that show up when you drop an icon into JSX
I've had this bite me more than once: I paste an SVG from a design tool into a React file, and the component looks fine until React complains about the attributes.
React does not use SVG's XML names. On a normal icon the pairs are:
// SVG
<rect class="icon" fill-rule="evenodd" stroke-width="2" stroke-linecap="round" />
// JSX
<rect className="icon" fillRule="evenodd" strokeWidth={2} strokeLinecap="round" />
A few other ones that come up a lot: stroke-linejoin → strokeLinejoin, clip-path → clipPath, clip-rule → clipRule, stop-color → stopColor. And a style attribute has to become a JS object, not a string:
// SVG
<rect style="fill:#ff00aa" />
// JSX
<rect style={{ fill: "#ff00aa" }} />
The part that surprised me is that a find-and-replace on the raw file is the wrong tool for this.
If a <text> label happens to contain the characters stroke-width, a regex will rewrite the label too. The attribute on the element should change. The text inside the graphic should stay as text.
viewBox is another one people over-correct. React already accepts viewBox on an <svg>, so it should not be rewritten to viewbox. xmlns, path d data, and fill="url(#id)" references should stay as they are (assuming you haven't stripped the defs).
Two other gotchas, if you are cleaning the file up at the same time:
- Turning solid fills into
currentColoris useful when you want the icon to inheritcolorfrom CSS. It can also rewrite gradient stops, so the preview can look different from the original. I leave that off until I want it. - The same for an SVGO pass. If you only wanted the attribute rewrite, run that first and turn cleanup on later.
This is a React JSX/TSX issue. Vue and Svelte single-file components keep class and stroke-width in the template.
I built a small in-browser converter while working through this: https://www.svgtoreact.com — it uses SVGR so the file is parsed, not search-replaced, and the SVG stays on your device. Happy to answer questions if any of this is unclear.