Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  132] [ 7]  / answers: 1 / hits: 169723  / 10 Years ago, thu, may 1, 2014, 12:00:00

Is it possible to embed SVG markup into a ReactJS component?


render: function() {
return (
<span>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmln ...
</span>
);
}

Results in the error:



Namespace attributes are not supported. ReactJSX is not XML.



What is the lightest way of doing this. Using something like React ART is way overkill for what I'm trying to do.


More From » svg

 Answers
12

Update 2016-05-27


As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (classclassName, style="color: purple"style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with <defs>, <use>, and inline styles:


function SvgWithXlink (props) {
return (
<svg
width="100%"
height="100%"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<style>
{ `.classA { fill:${props.fill} }` }
</style>
<defs>
<g id="Port">
<circle style={{fill:'inherit'}} r="10"/>
</g>
</defs>

<text y="15">black</text>
<use x="70" y="10" xlinkHref="#Port" />
<text y="35">{ props.fill }</text>
<use x="70" y="30" xlinkHref="#Port" className="classA"/>
<text y="55">blue</text>
<use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
</svg>
);
}

Working codepen demo


For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.




Previous answer


You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:


        render: function() {
return (
<svg viewBox="0 0 120 120">
<circle cx="60" cy="60" r="50"/>
</svg>
);
}

At which point you can think about adding props like fill, or whatever else might be useful to configure.


[#71223] Tuesday, April 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
natalyah

Total Points: 371
Total Questions: 90
Total Answers: 105

Location: The Bahamas
Member since Wed, Apr 12, 2023
1 Year ago
natalyah questions
;