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;