You can use the fetch API or the Axios library to request the HTTP if you want to dynamically load an SVG image and replace a tag with the actual SVG code in a React component. Here’s an example using the fetch API:
1. Create Custom hooks
eg: path: app/logic/useSvgLoader.js
import React, { useEffect, useState } from "react";
const useSvgLoader = ({ svgPath }) => {
const [svgData, setSvgData] = useState("");
useEffect(() => {
const loadImage = async () => {
try {
const response = await fetch(svgPath);
const data = await response.text();
console.log(data, "data");
setSvgData(data);
} catch (error) {
console.error("Error loading SVG:", error);
}
};
loadImage();
}, []);
return { svgData };
};
export default useSvgLoader;
1. Import this Hooks to your Components
import useSvgLoader from "@/logic/useSvgLoader";
const demoComponents = ({ data }) => {
const svgPath = "/images/download.svg";
const { svgData } = useSvgLoader({ svgPath });
return (
{svgData && (
<div dangerouslySetInnerHTML={{ __html: svgData }} />
)}
)
})
In this example, the useSvgLoader custom hook takes the SVG path as a parameter, handles the loading logic, and returns the SVG data. The SvgLoader component then uses this custom hook to load and display the SVG.
Make sure to replace ‘path/to/your/svg/image.svg’ with the correct path to your SVG file.
Top comments