Skip to content
Advertisement

Putting label array to the chartjs?

I have these codes: let arr = [];

  items &&
    items.map((index) => {
      arr.push(index.itemName);
    });

This is what console.log(arr); shows:

[“Item1”, “Item2”, “Item3”, “Item4”]

Below is my graph: How can I loop through the object arr to be put inside the labels?

   <Pie
        data={{
          labels: , <-- How can I loop through all of the `arr` here?
          datasets: [
            {
              label: "1st Dose",
              data: [10, 20, 30, 50, 30],
              backgroundColor: ["red", "orange", "yellow", "Green", "Blue"],
              borderColor: ["rgba(255, 99, 132, 1)"],
              borderWidth: 1,
            },
          ],
        }}
        height={400}
        width={600}
        options={{
          maintainAspectRatio: false,
          title: {
            display: true,
            text: "Hello",
            fontSize: 20,
          },
          legend: {
            labels: {
              fontSize: 25,
            },
          },
        }}
      />

Advertisement

Answer

The charts label receives a string or an array of strings:

interface ChartData {
  labels?: Array<string | string[]>;
  datasets?: ChartDataSets[];
}

So you will put your array directly to the labels like so:

data={{
  labels: arr,
  datasets: [
    {
      label: "1st Dose",
      data: [10, 20, 30, 50, 30],
      backgroundColor: ["red", "orange", "yellow", "Green", "Blue"],
      borderColor: ["rgba(255, 99, 132, 1)"],
      borderWidth: 1,
    },
  ],
}}

A live example for you to follow:

Edit chart.js (forked)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement