그냥
chart.js
에 있는 reference 코드는 자바스크립트에서 사용하는 것이어서 리액트로 연동하는 것이 매우 곤란.. 그래서 사용한 것이react-chartjs-2
import React from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import faker from 'faker';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
chart.js 에서 import를 해주고 다시 ChartJS에 register를 해준다.
export const options = {
responsive: true,
interaction: {
mode: "index",
intersect: false,
},
tension: 0.3,
plugins: {
legend: {
position: "bottom",
},
},
scales: {
x: {
grid: {
display: false,
},
},
y: {
grid: {
display: false,
},
},
},
};
option은 chart에 여러가지 옵션을 줄 수 있다. responsive의 경우 크기를 변경하기 위해서는 false로 지정. interaction의 mode를 index로 설정할 경우 index를 기준으로 tooltip을 띄어준다. plugins은 legend를 위, 아래로 지정해줄 수 있다. scales은 x축, y축의 기준선을 지워줄 수 있다.
const generateLabels = () => {
const years = [];
for (var i = 2000; i < 2023; i++) {
years.push(i);
}
return years;
};
const labels = generateLabels();
export const data = {
labels,
datasets: [
{
label: "Board Games",
data: [
47, 97, 163, 250, 347, 453, 550, 665, 805, 958, 1126, 1313, 1535, 1758,
2007, 2322, 2677, 3065, 3461, 3876, 4162, 4398, 4429,
],
borderColor: "#A98E64",
backgroundColor: "#F3F0EC",
fill: "origin",
},
],
};
export function App() {
return <Line options={options} data={data} />;
}
labels는 x-axis의 레이블.. 위와 같은 경우는 for문을 돌려서 2000년~2022년까지의 레이블을 array로 넘겨줌.. data는 y-axis이다.. 나는 간단한 데이터여서 그냥 array로 넘겨줬음..
fill
설정은 import 부분에Filler
를 추가해줘야 한다. "origin"은 기존 chart를 가르키고, dataset이 많아지면 1, 2, 3....이런식으로 설정해준다. 마지막으로 Line 컴포넌트를 넘겨주면 끝!
할 수 있어.....