I have an link which has the svg file with the format of svg . svgfilelink
And this link has the following content :
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20px" height="20px" viewBox="0 0 20 20" version="1.1">
<title>Rectangle Copy 14</title>
<defs>
<linearGradient x1="5.7671933%" y1="50.1613046%" x2="99.3732272%" y2="50.1613046%" id="linearGradient-1">
<stop stop-color="#59D08F" offset="0%"/>
<stop stop-color="#26C2DC" offset="100%"/>
</linearGradient>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="06-Shapes-Properties" transform="translate(-1166.000000, -354.000000)" stroke="url(#linearGradient-1)" stroke-width="2">
<rect id="Rectangle-Copy-14" x="1167" y="355" width="18" height="18"/>
</g>
</g>
As of now I'm adding this link as src in img tag . But I need this link as svg format. I have tried few methods. But didn't help. Is there any possible ways to convert the url into svg tag in JAVASCRIPT?
CodePudding user response:
If you used create-react-app
, it already uses @svgr/webpack
package, so you can do this, which will cause the image to load inline as React components containing the SVG elements directly, instead of by a link:
import { ReactComponent as RectangleIcon } from './rectangle.svg';
export const MyComponent = () => {
return <RectangleIcon />
}
If you are not using create-react-app so not using svgr yet, you can add it to your project (see docs)
CodePudding user response:
I don't know if this is the right way to do but you can directly fetch that svg and render it to the DOM using innerHTML
or something like dangerouslySetInnerHTML
with react
let svgUrl = 'https://raw.githubusercontent.com/rahuldkjain/github-profile-readme-generator/master/src/images/icons/Social/hackerrank.svg'
function getTheSvg(url) {
return fetch(url).then(res => res.text());
}
getTheSvg(svgUrl).then(res => {
let svgDiv = document.querySelector('.svg')
svgDiv.innerHTML = res
})
svg {
height: 200px
}
<div class='svg'><div>