Search code examples
reactjstypescriptchart.jsreact-chartjs-2

React Chart.JS cant move legend (TypeScript)


I have a Doughnut chart component with this data:

  const data = {
    labels: ["1", "2"],
    datasets: [
      {
        label: "peers",
        data: [1, 2],
        backgroundColor: ["#56E2CF", "#56AEE2"]
      }
    ]
  };

The data works right. These are the options:

  const options = {
    legend: {
      display: "right"
    }
  };

Component Doughnut:

<Doughnut data={data} options={options} />

But the chart still has no title: enter image description here


I have tried to put the options in char.js style, using plugins:

  const options = {
    plugins: {
      legend: {
        position: "right"
      }
    }
  };

The legend moves but i get a type error (still no title): The types of 'plugins.legend.position' are incompatible between these types. Type 'string' is not assignable to type '"right" | "left" | "top" | "bottom" | "center" | "chartArea" | _DeepPartialObject<{ [scaleId: string]: number; }> | undefined'

Notice how the caption has moved to the right: enter image description here


Solution

  •  const options = {
        plugins: {
          legend: {
            position: "right" as const
          },
          title: {
            display: true,
            text: "Title"
          }
        }
      };
    

    Here is an explanation from TypeScript docs - https://devblogs.microsoft.com/typescript/announcing-typescript-3-4-rc/#const-assertions