Spongi
Spongi

Reputation: 549

Export a nivo chart/diagramm as image in React

I am using a nivo library for charts. I want to export as a PNG/JPEG image some react component that are using a ResponsiveBar internally. The problem is this functionality is not built-in in the library. I have components structure like this:

<MyComponent>
  <ResponsiveBar />
</MyComponent>

I need a function that takes as param this kind of React component and returns an image. Something like this:

exortChartToPng(chartComponent);

Upvotes: 4

Views: 1668

Answers (1)

Roozbeh
Roozbeh

Reputation: 742

Simply use dom-to-image-more like bellow:

npm install dom-to-image-more
import React, { useRef } from 'react';
import { ResponsiveBar } from '@nivo/bar';
import domtoimage from 'dom-to-image-more';

const MyComponent = () => {
  const chartRef = useRef(null);


  const exortChartToPng = () => {
        if (chartRef.current) { //Type Guard
            domtoimage
                .toPng(chartRef.current, {
                    width: chartRef.current.offsetWidth * 3, // Image quality stuff
                    height: chartRef.current.offsetWidth * 3,
                    quality: 1,
                    style: {
                        transform: 'scale(' + 3 + ')',
                        transformOrigin: 'top left'
                    }
                })
                .then(function (dataUrl) {
                    const link = document.createElement('a');
                    link.href = dataUrl;
                    link.download = 'chart.png';
                    link.click();
                })
                .catch(function (error) {
                    console.error('Error exporting chart:', error);
                });
        }
    };

  return (
    <div>
      <button onClick={exortChartToPng}>Export Chart</button>
      <div ref={chartRef}>
        <ResponsiveBar
          data={yourData} // Replace `yourData` with your actual chart data
          // Configure other chart props as needed
          // ...
        />
      </div>
    </div>
  );
};

export default MyComponent;

Upvotes: 0

Related Questions