Chart.jsで円グラフを表示する
Next.js
Chart.js
フロントエンド
知識
API側でデータを準備してあげて、Doughnutのdataに登録する。
tsx
'use client';
import React from 'react';
import { Doughnut } from 'react-chartjs-2';
import {
Chart as ChartJS,
ArcElement,
Tooltip,
Legend,
type ChartData,
} from 'chart.js';
ChartJS.register(ArcElement, Tooltip, Legend);
const options = {
plugins: {
legend: {
labels: {
padding: 8,
},
},
},
};
export const Container = (): JSX.Element => {
const { data } = useGetMeDashboard();
if (!data) {
return <LinearLoading />;
}
const labels = data.categoryItemCounts
? data.categoryItemCounts.map((item) => item.categoryName)
: ['データなし'];
const datasetsData = data.categoryItemCounts
? data.categoryItemCounts.map((item) => item.itemCount)
: [1];
const categoryItemCountsLength = data.categoryItemCounts?.length ?? 1;
const baseColor = data.categoryItemCounts ? '#F9BD46' : '#FDE08F';
// pieChartData作成
const pieChartData: ChartData<'doughnut'> = {
labels,
datasets: [
{
data: datasetsData,
backgroundColor: generateBackgroundColors(
baseColor,
categoryItemCountsLength
),
borderWidth: 1,
spacing: 2,
},
],
};
<Doughnut
data={pieChartData}
options={{
...options,
maintainAspectRatio: true, // アスペクト比を維持
responsive: true, // レスポンシブ対応
}}
/>;
};