Home > database >  fetch svg from the WEB and use it as <svg /> in React (NEXT.js)
fetch svg from the WEB and use it as <svg /> in React (NEXT.js)

Time:01-26

I have an API that contains .svg files.

That API is being consumed by a NEXT.js application

The files are loaded like this <img src="https://api.com/image.svg" />, but that way styles cannot be applied to the svg paths.

I need to load the svg element like that: <svg> <path d='...'/></svg> so i can style it. (for example change the color of it, since the svg has fill=currentColor applied.)

I know that there are webpack plugis like SVGR that can load and svg as a component, if it is placed in the public folder but they do not seem to work with online svg files.

Is there any way I can do that?

CodePudding user response:

                        var xhr = new XMLHttpRequest();
                        xhr.open('GET', 'https://api.com/image.svg');
                        xhr.addEventListener('load', function(ev)
                        {
                            var xml = ev.target.response;
                            var dom = new DOMParser();
                            var svg = dom.parseFromString(xml, 'image/svg xml');

                            document.body.appendChild(svg.rootElement);
                        
                        });
                        xhr.send(null);
  • Related