Embedding SVG into ReactJS
Asked Answered
C

7

158

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.

Culdesac answered 1/5, 2014 at 5:29 Comment(2)
Can you create a jsbin? It might be as simple as changing your opening SVG tag to just <svg id="Layer_1"> (or even better, without the id). Edit: here's an example: jsbin.com/nifemuwi/2/edit?js,outputDisincline
@FakeRainBrigand Thanks! It was that simple in this case. Look at Ben's answer though. Good to know you can get around the jsx parsing when you need to.Culdesac
M
217

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.

Marlie answered 1/6, 2015 at 17:40 Comment(5)
@ChinonsoChukwuogor Great question! I don’t know, I’ve never used React Native. Did you give it a go?Marlie
@AndrewPatton Multiple Css Class names with the tick char does not work: '.class1, .class2{fill: #005baa;}' How can I fix that?Dobson
@Dobson Can you give me an example where it doesn’t work? I just forked my original demo to add classB and it worked: codepen.io/acusti/pen/BVJzNgMarlie
Thanks, starting from this I've managed to import an svg from file as a React component without any loader, I've just removed ``` xmlns:osb="openswatchbook.org/uri/2009/osb"``` from the svg tag, leaving only the xlmns. It's all about tag parsing apparently. Just in case, I've followed these steps as well: blog.logrocket.com/how-to-use-svgs-in-reactIneradicable
Why do people tolerate JSX?Mensch
U
62

If you just have a static svg string you want to include, you can use dangerouslySetInnerHTML:

render: function() {
    return <span dangerouslySetInnerHTML={{__html: "<svg>...</svg>"}} />;
}

and React will include the markup directly without processing it at all.

Unship answered 1/5, 2014 at 17:41 Comment(2)
I'm controlling some paths inside SVG using React, but React doesn't seem to support the filter elements. Is there a way to support this? Seems like dangerouslySetInnerHTML won't work because I can't put a span inside an SVG and I can't use that to set the filter attribute on the paths. I don't suppose there's a way to create React elements as usual but have them pass all attributes verbatim to the DOM elements?Peasant
As 2019, seems that you can use dangerouslySetInnerHTML but still I couldn't make shadow filter to work on Chrome using dangerouslySetInnerHTML, but it's working on Firefox.Swinge
T
34

According to a react developer, you dont need the namespace xmlns. If you need the attribute xlink:href you can use xlinkHref from react 0.14

Example

Icon = (props) => {
  return <svg className="icon">
    <use xlinkHref={ '#' + props.name }></use>
  </svg>;
}
Traherne answered 8/11, 2015 at 10:46 Comment(0)
M
16

If you want to load it from a file, you may try to use React-inlinesvg - that's pretty simple and straight-forward.

import SVG from 'react-inlinesvg';

<SVG
  src="/path/to/myfile.svg"
  preloader={<Loader />}
  onLoad={(src) => {
    myOnLoadHandler(src);
  }}
>
  Here's some optional content for browsers that don't support XHR or inline
  SVGs. You can use other React components here too. Here, I'll show you.
  <img src="/path/to/myfile.png" />
</SVG>
Madison answered 20/1, 2017 at 4:43 Comment(0)
M
7

You can import svg and it use it like a image

import chatSVG from '../assets/images/undraw_typing_jie3.svg'

And ise it in img tag

<img src={chatSVG} className='iconChat' alt="Icon chat"/>
Misti answered 7/10, 2020 at 4:51 Comment(3)
The question asks for embedding svg inline specifically.Bowstring
so what if you need to change the color?Nematode
I believe this isn't what's originally askedLacee
D
4

The best way I found was this site

https://react-svgr.com/playground/

You copy an svg and it give you a react functional component with the svg transformed to react code.

Doubly answered 25/1, 2021 at 22:35 Comment(0)
C
2

There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.

https://www.npmjs.com/package/convert-svg-react

Cilia answered 2/11, 2020 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.