reactjs - Display SVG string in the React frontend - Stack Overflow

时间: 2025-01-06 admin 业界

I have encountered an issue while displaying a scraped SVG string on the frontend in a React application. Here's a brief overview of the process:

  1. I used Node.js and Puppeteer to scrape a price chart (in SVG format) from a website (as shown in the image below)

  2. I created an API to serve the scraped SVG data and successfully fetch it on the frontend using fetch.

  3. On the React frontend, I attempted to render the SVG using dangerouslySetInnerHTML. However, the API's response is a long string, and I am unsure how to correctly handle and display it.

If anyone with experience in working with SVGs, Puppeteer, or similar scenarios could provide guidance or suggest best practices for rendering the scraped SVG in React, I would greatly appreciate it.

Here's the code I developed:

const SvgChart: React.FC = () => {
  const [svg, setSvg] = useState<string | null>(null);

  useEffect(() => {
    const fetchSvg = async () => {
      try {
        const response = await fetch('http://localhost:3000/api/svg-chart');
        const data = await response.json();
        setSvg(data.svg);
      } catch (error) {
        console.error('Error fetching SVG:', error);
      }
    };

    fetchSvg();
  }, []);

  return (
    <div>
      {svg ? (
        <div dangerouslySetInnerHTML={{ __html: svg }} />
      ) : (
        <p>Loading chart...</p>
      )}
    </div>
  );
};

export default SvgChart;