I have a dynamic SVG which I've got as a return value from an API, this API contains several HTTP calls inside so I can't display it in a <img src={svg} />
tag.
The SVG which I try to display can be found here: https://www.svgviewer.dev/s/g4PDWSVs
I use React Vite, with the SVGR plugin for Vite, when I copy the SVG data from the API, and store it as a file: ticket.svg, I am able to display it like this. However I don't want to store it in a file before displaying it, I want to directly display it in my JSX without manually having to make a .svg file for every SVG
Here is the code which I am currently using where I hardcoded ticket.svg as a file and display it as a React Component successfully, however my goal is to display the svg directly from the ticketSvg stored in state.
import { ReactComponent as Ticket } from "./../../assets/ticket.svg";
const TicketDetail = () => {
const [ticketSvg, setTicketSvg] = useState();
const getTicketSVG = () => {
// ...fetching SVG here
setTicketSvg(svg); // looks something like <svg> ...svgData here..</svg>
};
return (
<header className={styles.header}>
// display svg here
<Ticket />
</header>
);
};
I have also tried to use a tag, but in this case only the frame of the SVG will be displayed but the HTTP calls in the SVG won't execute.
<img src={`data:image/svg+xml;utf8,${encodeURIComponent(ticketSvg)}`} />
Some of the resources I tried, but without result:
- Turning an SVG string into an image in a React component
- How to dynamically import SVG and render it inline
- Unable to import SVG with Vite as ReactComponent
Any help would be greatly appreciated!
Edit
- Result for using
<img src={svg} />
ERROR: GET http://localhost:5174/ticket-detail/.....[HTTP/1.1 404 Not Found 1ms]
- Result for using
<img src={`data:image/svg+xml;utf8,${encodeURIComponent(ticketSvg)}`} />
The images which should be retrieved from the API calls inside the SVG don't get executed, as you can see the QR code and logo's aren't being displayed.