11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】react-chartjs-2で『Error: "category" is not a registered scale.』のエラーが出る対処

Last updated at Posted at 2022-07-23

はじめに

Reactでグラフの描画をしようと、サクっと日本語記事からコピペでやろうと思ったらハマったので対処法を残しておきます。

ちなみに当初コピペして以下の書き方で色々試していました。

NG例1:Graph.tsx
import { Line } from "react-chartjs-2";

~~~~~以下略~~~~~
NG例2:Graph.tsx
import { Chart as ChartJS, registerables } from 'chart.js';
import { Chart } from 'react-chartjs-2'
ChartJS.register(...registerables);

~~~~~以下略~~~~~

原因:v4になって書き方が若干変わったっぽい

バージョンによってimportのやり方が結構違うようです。
v4系の折れ線グラフの実装例を載っけておきます。

OK例:Graph.tsx
import React from "react";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Line } from "react-chartjs-2";

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

const Graph: React.FC = () => {
  const options = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: "グラフタイトル",
      },
    },
  };

  const labels = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
  ];

  const data = {
    labels,
    datasets: [
      {
        label: "データ1",
        data: [10, 40, 30, 40, 50, 80, 120],
        borderColor: "rgb(255, 99, 132)",
        backgroundColor: "rgba(255, 99, 132, 0.5)",
      },
    ],
  };

  return (
    <>
      <Line options={options} data={data} />
    </>
  );
};

export default Graph;

検証バージョン

  • chart.js: ^3.8.0
  • react-chartjs-2: ^4.3.1

さいごに

ちゃんと公式ドキュメントを見よう!

参考

11
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?