I currently have a Recharts component that I would like to export as a PNG file.
<LineChart
id="currentChart"
ref={(chart) => this.currentChart = chart}
width={this.state.width}
height={this.state.height}
data={this.testData}
margin={{top: 5, right: 30, left: 20, bottom: 5}}
>
<XAxis dataKey="name"/>
<YAxis/>
<CartesianGrid strokeDasharray="3 3"/>
<Tooltip/>
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{r: 8}}/>
<Line type="monotone" dataKey="uv" stroke="#82ca9d"/>
</LineChart>
but I'm unsure if this is directly supported by the library.
I have an idea that involves using a canvas and a 2D rendering context to get me close to a solution, as outlined on MDN
However, I'm not sure of a generic way to render an HTML element (or React Component) as a canvas to implement this solution.
I might be going about this all wrong, and I would appreciate the correction!
I was able to solve my problem by delving into the Recharts component. Recharts renders as an SVG under a wrapper so all I had to do was convert properly to save as both HTML or SVG
I am using FileSaver.js for the save prompt.
This function takes SVG element on input and transforms to
image/png
data:And how to access the Recharts SVG element? This code snippet allows you to render any Chart outside of your current visible DOM and use it's SVG: