0

I get a SVG from an API call which looks something like this:

<svg width="848" height="848" viewBox="0 0 848 848" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">xxxxxxxxx</svg>

Now I would like to display this SVG in my react component without having to create a seperate .svg file for each of my SVGs as shown in the SVGR docs like: import { ReactComponent as Ticket} from "./ticket.svg";

How can this be achieved in React vite? (with or without SVGR), the <img src={svg} /> method doesn't work for me either since it's a more complex SVG with some direct links/API calls

I am using the vite-plugin-svgr with:

vite.config

export default defineConfig({
  plugins: [svgr(), react()],
});

My component

const TicketDetail = () => {
  const [ticketSvg, setTicketSvg] = useState();

  const getTicketSVG = () => {
    // ...fetching SVG here

    setTicketSvg(svg); // looks something like <svg> xxxxxxxxxxx </svg>
  };

  return (
    <header className={styles.header}>
      // display svg here
      <svg>{ticketSvg}</svg>
    </header>
  );
};
Bram
  • 669
  • 3
  • 12
  • 25
  • Have you try this: https://stackoverflow.com/questions/44900569/turning-an-svg-string-into-an-image-in-a-react-component – Tony Jun 07 '23 at 02:34
  • Does this answer your question? [Turning an SVG string into an image in a React component](https://stackoverflow.com/questions/44900569/turning-an-svg-string-into-an-image-in-a-react-component) – Wongjn Jun 07 '23 at 07:34
  • These answers do not work since my SVG uses internal HTTP calls. – Bram Jun 07 '23 at 09:19

1 Answers1

0

If the SVG is interactive and/or otherwise complex, then you can put it in an iframe with the svg string being the srcdoc like this:

Given the recieved SVG...

var S='<svg width="848" height="848" viewBox="0 0 848 848" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">hello</svg>';

Then...

var I=document.createElement('iframe');

I.id='SvgHolder';

I.width=500;

I.height=300;

I.srcdoc=S;

document.body.appendChild(I);

Note: One can easily write a function to process multiple SVGs in this way, by passing X,Y,width, height and SVG string to it.

The beauty with an iframe is that you get to manage the security side of things.