Search code examples
reactjschart.jsreact-chartjs-2

React-chartjs-2: How to display timeline of released dates over 5 past years in Bar Chart?


Given a structure like this

const products = [
  {
    id: 1,
    status: "released"
  },
  {
    id: 2,
    status: "in progress"
  },
  {
    id: 3,
    status: "in progress"
  },
  {
    id: 4,
    status: "released"
  },
  {
    id: 5,
    status: "released"
  }
];

I'm trying to display a timeline of released dates over 5 past years.
As you can see, in the array of objects above, status property can be different. So my goal is to display the timeline for released objects in a chart assuming that every year is corresponding to the index of object in the array.
So,for the
1st object in the array will match with the year 2018.
second: 2019,
third: 2020 and so on.
But instead of highlighting all objects, chart should have a label for all the years and highlight only with the status of released.
I created an objects for labels like this
const labels = ["2018", "2019", "2020", "2021", "2022"],
but can't figure out to implement it in the chart. Here is Code example and sandbox link

import React from "react";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from "chart.js";
import { Bar } from "react-chartjs-2";
import faker from "faker";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: "top" as const
    },
    title: {
      display: true,
      text: "Chart.js Bar Chart"
    }
  }
};

const products = [
  {
    id: 1,
    status: "released"
  },
  {
    id: 2,
    status: "in progress"
  },
  {
    id: 3,
    status: "in progress"
  },
  {
    id: 4,
    status: "released"
  },
  {
    id: 5,
    status: "released"
  }
];

const labels = ["2018", "2019", "2020", "2021", "2022"];

export const data = {
  labels,
  datasets: [
    {
      label: "Dataset 1",
      data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
      backgroundColor: "rgba(255, 99, 132, 0.5)"
    },
    {
      label: "Dataset 2",
      data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
      backgroundColor: "rgba(53, 162, 235, 0.5)"
    }
  ]
};

export function App() {
  return <Bar options={options} data={data} />;
}

Any help will be appreciated


Solution

  • Not sure the result you are looking for, but the following code will generate a graph with a bar for each year that was released.

    const labels = ["2018", "2019", "2020", "2021", "2022"];
    
    export const data = {
      labels,
      datasets: [
        {
          label: "Released",
          data: products.map(p => p.status === "released" ? 1:0),
          backgroundColor: "rgba(255, 99, 132, 0.5)"
        }
      ]
    };
    
    export function App() {
      return <Bar options={options} data={data} />;
    }