Chartjs-React ChartJS, Blank White Screen (No Error)

0👍

you are missing some important points.

  1. I don’t know the version of chart.js that you use. But at v4, you need to register registerables:
    import { Chart, registerables } from "chart.js";
    ...
    Chart.register(...registerables);
    ...
  1. In react we use ref to access canvas element:
import { useRef } from react;

function MyChart() {
  const [canvasElRef, setCanvasElRef] = useRef(null)

  ...

  return (
    <canvas ref={canvasElRef} />
  )
}

  1. chart.js canvas element need a wrapper, and the canvas element must have an initial dimension for maintaining the responsive size (don’t forget the maintainAspectRatio: false in the chart options.
function MyChart() {
  ...  
    options: {
      responsive: true,
      maintainAspectRatio: false,
      ...
    }
  ...

  return (
    <div style={{ width: "100vw", height: "100vh" }}>  <--- use your own styling
      <canvas ref={canvasElRef} width="600" height="350" />
    </div>
  );
}
  1. You need to make sure that the data and canvas element are available before create Chart instance. Here you have to keep the instance at a ref so we can use it as reference for destroying the chart instance when unmount/cleanup process took place
  const [chartRef, setChartRef] = useRef(null)

  ...

  useEffect(() => {
    if (chartData && canvasElRef.current) {
      chartRef.current = new Chart(canvasElRef.current, {

      }
    }

    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current = null;
      }
    }
  }
  1. In v4, the title now is a part of plugins:
  options: {
    ...
    plugins: {
      title: {
        display: true,
        text: "Daily Percentage Returns of SPY",
      },
    },
  }
  1. Chartjs moment adapter is the most important thing when using a time series chart. So you need to import it after importing chart.js
import { useCallback, useEffect, useState, useRef } from "react";
import { ChartData, Chart, registerables } from "chart.js";
import "chartjs-adapter-moment";  <---- import here

Chart.register(...registerables);

And finaly, you can check the final code here

Leave a comment