はじめに
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
さいごに
ちゃんと公式ドキュメントを見よう!
参考