I want to display the chart image rather than the chart from react-chartjs-2 and chart.js.
However, the image is never fully rendered at first
export function App() {
const chartRef = useRef<ChartJS>(null);
const [chartImg, setChartImg] = useState<string>();
const ChartRef = () => <Chart ref={chartRef} type="line" data={data} />;
useEffect(() => {
const chart = chartRef.current;
if (!chart) return;
const img = chart.toBase64Image(); // just white background
setChartImg(img);
}, []);
const showImage = useCallback(() => {
const chart = chartRef.current;
if (!chartRef.current) return;
const img = chart.toBase64Image(); // Correct image is displayed
setChartImg(img);
}, []);
return (
<div>
<ChartRef />
<button type="button" onClick={showImage}>
Display Image
</button>
<img src={chartImg} alt="here" />
</div>
);
}
In the following code (linked codesandbox here), the image is not displayed until I click on the Display Image
button.
Is there any way I can run an initial check on useEffect
and make sure the image is correctly displayed instead of chart without having to click on Display Image
for example?