'React Rendering for Image Download
On different screens users will observe a responsive chart that adjusts its dimensions to the screen’s resolution. When the user clicks a download button a new chart with fixed dimensions should be added to the DOM outside of the user’s view. I want to select the svg with fixed dimensions and then download the chart as a png.
I added a prop to the parent element to show or hide the chart when the downloadImage function is called. As a result, I have to wait for the render to complete before selecting the svg. The problem I have run into is that the axis are drawn on the first render, but the lines of the chart are only added if I wait for an arbitrary amount of time before performing my document selection.
const downloadImage = (setAddDownloadableChartToDOM) => {
// Toggle the chart's visibility in the DOM
setAddDownloadableChartToDOM(true);
// Create a new div to hold the elements for the image
const screenshot = document.createElement("div");
document.body.appendChild(screenshot);
screenshot.id = "screenshot";
screenshot.style.cssText = "width: 1920px;height: 1080px;";
// Create a new div to hold the elements for the image
// SetTimeout used to await the rendering of the newly mounted line chart component
setTimeout(() => {
const chart = document.getElementById("downloadable-chart");
screenshot.append(chart);
const chartImageToDownload = document.getElementById("screenshot");
// Then download the file and remove the screenshot from the DOM
toPng(chartImageToDownload)
.then((dataUrl) => downloadFile(dataUrl, "my-download.png"))
.then(() => {
setAddDownloadableChartToDOM(false);
document.body.removeChild(screenshot);
})
.catch((err) => {
console.log("Error", err);
document.body.removeChild(screenshot);
});
}, 5000);
};
How do I compose a function to wait for the svg to be finished drawing or for the React component to be fully mounted before selecting the svg?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
