Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-chartjs-2 mixed type chart doesn't work with type in datasets

    labels: ['2021-10-29', '2021-10-30', '2021-10-31', '2021-11-01', '2021-11-02', '2021-11-03', '2021-11-04'],
    datasets: [
      {
        label: 'Coaching',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(98.100.24)`,
      },
      {
        label: 'Away',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(202,214,219)`,
      },
      {
        label: 'Total Call Count',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(${rand()},${rand()},${rand()})`,
        type: 'line',
      },

<Bar data={chartData}/>

When I run this on react, this gives me the error like the below

  Type '{ labels: string[]; datasets: ({ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; })[]; }' is not assignable to type 'ChartData<"bar", number[], string>'.
    Types of property 'datasets' are incompatible.
      Type '({ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; })[]' is not assignable to type 'ChartDataset<"bar", number[]>[]'.
        Type '{ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type 'ChartDataset<"bar", number[]>'.
          Type '{ label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type 'ChartDataset<"bar", number[]>'.
            Type '{ label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type '_DeepPartialObject<{ type: "bar"; } & BarControllerDatasetOptions>'.
              Types of property 'type' are incompatible.
                Type 'string' is not assignable to type '"bar" | undefined'.
    276 |           </Box>
    277 |           <Box className={classes.historyChart}>
  > 278 |             <Bar data={chartData} options={chartOptions} />
        |                  ^^^^
    279 |           </Box>
    280 |         </>
    281 |       )}

Can anyone help me to make this work? I can't seem to find any solution on internet

like image 302
Ian Kang Avatar asked Sep 17 '25 17:09

Ian Kang


2 Answers

The type definitions are overly restrictive. You can work around this by casting to any.

type: 'line' as any,
like image 100
Adam Siler Avatar answered Sep 20 '25 07:09

Adam Siler


Try making these changes and see if it works for you:

  1. type: 'line' as const
  2. <Chart type='bar' data={chartData} /> (ensure you import Chart from react-chartjs-2).
like image 33
Peter Umoren Avatar answered Sep 20 '25 07:09

Peter Umoren