Is is 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.
This question is related to
javascript
svg
reactjs
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.
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"/>
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>;
}
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.
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>
There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.
Source: Stackoverflow.com