Home > Software design >  Setting type for React Typescript component attribute
Setting type for React Typescript component attribute

Time:05-22

I keep getting ts error #2741 (Property 'datasets' is missing in type). See img below

For the life of me I cannot figure out how to set type for the data attribute of the <Bar /> component. I've tried data: string[] inline and so many other variations.

import { Bar } from 'react-chartjs-2';

import './Chart.css';

export default function Chart() {
  return (
    <div className="data">
      Chart
      <Bar
        data={{
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
        }}
        height={400}
        width={400}
        options={{
          maintainAspectRatio: false
        }}
      />
    </div>
  )
}

CodePudding user response:

datasets is a required property of the data type. In your example you only provided the labels property, thus typescript is throwing that error.

A valid data object should look like this:

data: {
    datasets: [{
      data: [20, 10],
    }],
    labels: ['a', 'b']
}

From chartjs docs:
https://www.chartjs.org/docs/latest/general/data-structures.html

CodePudding user response:

You need to fix the data you are giving your Bar component data the should look something like this as suggested from the Chart JS Docs

data: {
 datasets: [{
   data: [20, 10],
 }],
 labels: ['a', 'b']
}

Note: When the data is an array of numbers, values from labels array at the same index are used for the index axis (x for vertical, y for horizontal charts).

  • Related