1

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?

farooq
  • 1,603
  • 2
  • 17
  • 33
  • Tried this ? `` ? – Raptor Apr 25 '22 at 06:59
  • @Raptor . That is what I'm currently using. But I can't be able to change the fill color and other attributes of svg via image tag. So I'm actually looking for getting the svg value and append it as innerhtml inside a div tag – farooq Apr 25 '22 at 07:12
  • I think you mean _URL_, not "link". If you want to get the SVG source code from that URL - then you will need to make an HTTP request (AJAX/fetch/...) to get it. – CBroe Apr 25 '22 at 07:14
  • @farooq look at this new method introduced recently: https://stackoverflow.com/a/70986923/188331 – Raptor Apr 25 '22 at 07:20
  • Does this answer your question? https://stackoverflow.com/questions/34097191/using-a-svg-file-in-html-from-a-url – cSharp Apr 25 '22 at 07:27

2 Answers2

1

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>
norbekoff
  • 1,719
  • 1
  • 10
  • 21
1

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)

casraf
  • 21,085
  • 9
  • 56
  • 91