패키지 설치
npm install chartjs react-chartjs-2
chartjs 뿐만 아니라 react에서 chart를 렌더링하기 위한 react-chartjs-2도 설치해야한다.
Chart 그리기
1) 사용할 chart 요소 등록하기 (register)
react에서 chartjs를 사용하려면 컴포넌트를 불러오는 것 뿐만 아니라 사용할 컴포넌트들을 register하는 과정이 필요하다.
import React from 'react';
import { Bar } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
Title,
Tooltip,
Legend,
BarElement,
} from 'chart.js';
import { css } from '@emotion/react';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
2) Bar 컴포넌트 불러오기
인자로는 차트에 표시할 data와 options를 내려주면 된다.
return (
<div css={chartBoxStyle}>
<Bar data={data} options={options} />
</div>
);
3) data 및 options 설정
const [ratings, setRatings] = useState([
{ stars: 1, count: 100 },
{ stars: 2, count: 230 },
{ stars: 3, count: 700 },
{ stars: 4, count: 500 },
{ stars: 5, count: 520 },
]);
const [data, setData] = useState({
labels: ratings.map((item) => `${item.stars}점`),
datasets: [
{
label: '별점 분포',
data: ratings.map((item) => item.count),
borderWidth: 1,
},
],
});
const options = {
responsive: true,
maintainAspectRatio: false, // 차트 크기 조정 허용
scales: {
x: {
grid: {
display: false, // bar 구분하는 격자 숨김
},
},
y: {
beginAtZero: true,
grid: {
display: false, // 눈금 격자 숨김
},
ticks: {
display: false,
callback: function (value: any, index: any, values: any) {
return value.toLocaleString();
},
},
},
},
};
차트의 크기를 반응형으로 조정하고 싶다면?
options에서 responsive와 maintainAspectRation를 다음과 같이 설정해준다.
const options = {
responsive: true,
maintainAspectRatio: false,
// ...
}
그리고 width를 설정할 때 고정 크기로 지정하는게 아니라 max-width를 지정해줘서 줄어드는 것이 자유롭도록 한다.
const chartBoxStyle = css`
margin: auto;
max-width: 600px;
`;
'프로젝트 과정 기록' 카테고리의 다른 글
[Project] Youtube Party 만들기 (1) - 프로젝트 환경설정 | Nextjs + Typescript + Express (0) | 2023.09.23 |
---|---|
[Project] Youtube Party 만들기 - 프로젝트 주제, 컨셉 (0) | 2023.09.22 |
[JS] Chartjs 막대그래프 그리기 (별점 분포 차트) (0) | 2023.08.03 |
[React] 회원가입 유효성 검사 구현하며 겪은 시행착오와 react-hook-form 사용 (0) | 2023.07.31 |
[React] 카카오 지도 API - 키워드로 장소 검색하고 목록으로 보여주기 구현 +) Typescript (0) | 2023.07.17 |