Home > Enterprise >  using react ionic 6 with chartJS
using react ionic 6 with chartJS

Time:11-30

I'm trying to render a graph with ionic react but i keep getting errors such as:

Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused.

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

const Graph: React.FC = (props) => {
  const data = {
    labels: ["Billable", "Non Billable"],
    datasets: [
      {
        label: "Billable Vs. Non Billable",
        backgroundColor: ["#36a2eb", "rgba(255,99,132,0.2)"],
        borderColor: "rgba(255,99,132,1)",
        borderWidth: 1,
        hoverBackgroundColor: "rgba(255,99,132,0.4)",
        hoverBorderColor: "rgba(255,99,132,1)",
        data: [65, 59],
      },
    ],
  };

  return (
    <div>
      <h2>bar example</h2>

      <Bar
        data={data}
        width={100}
        height={50}
        options={{ maintainAspectRatio: false }}
      />
    </div>
  );
};

export default Graph;

does anyone knows how to solve it?

CodePudding user response:

I have found a solution, credit to @TechMaze from this post.

I had to import CategoryScale from chart.js and Chart from chart.js/auto.

it seems that Chart from chart.js wont solve this issue(!)

import { Bar } from "react-chartjs-2";
import { CategoryScale } from "chart.js";
import { Chart as ChartJS } from "chart.js/auto";
import {
  IonTitle,
  useIonViewWillEnter,
  useIonViewWillLeave,
} from "@ionic/react";

const Graph: React.FC = () => {
  useIonViewWillEnter(() => {
    ChartJS.register(CategoryScale);
  }, []);

  useIonViewWillLeave(() => {
    ChartJS.unregister(CategoryScale);
  }, []);

  const data = {
    labels: ["Billable", "Non Billable"],
    datasets: [
      {
        label: "Billable Vs. Non Billable",
        backgroundColor: ["#36a2eb", "rgba(255,99,132,0.2)"],
        borderColor: "rgba(255,99,132,1)",
        borderWidth: 1,
        hoverBackgroundColor: "rgba(255,99,132,0.4)",
        hoverBorderColor: "rgba(255,99,132,1)",
        data: [65, 59],
      },
    ],
  };

  return (
    <>
      <IonTitle>Bar Example</IonTitle>
      <Bar data={data} />
    </>
  );
};

export default Graph;

  • Related