[React.js + Typescript] Chart.js 사용하기

준이·2023년 3월 14일
0

React+Next.js+Typescript 환경에서
Chart.js 라이브러리 사용 기록을 남겨본다.
(누군가에게 도움이 됐으면 좋겠음..!)

react 환경에서 chart.js를 사용하려면 기본이 되는
chart.js와 chart.js를 react 환경에서 렌더링 하기 위한
react-chartjs-2를 설치해줘야 한다.

react-chartjs-2 + chart.js 설치

npm install react-chartjs-2 chart.js

react-chartjs-2 홈페이지
chart.js 홈페이지

두 홈페이지를 잘 참고해서 작성하면 react+typescript 환경(본인의 경우 어드민 페이지)에서 chart.js를 잘 구현할 수 있다.

기본적인 구조는 다음과 같다.

1. 기본적인 구조(ex. Line 차트)

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
);


export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'Chart.js Line Chart',
    },
  },
};

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

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
    },
    {
      label: 'Dataset 2',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(53, 162, 235)',
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

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

필자는 ref를 사용해 필터 등에 따른 차트의 조정을 해야했기 때문에 Chart 컴포넌트에 type을 주는 식으로 차트를 표현했다.

2. Ref

import { Chart } from "react-chartjs-2";

// typescript에서 chart.js ref 선언은 이런 식으로..!
const chartRef = useRef<ChartJS<"line", number[], string>>(null);

// 중간 생략
export function App() {
  return <Chart ref={chartRef} type={"line"} options={options} data={data} />;

ref를 활용해 ref.current.~로 원하는 요소값을 조정해준다(본인의 경우는 필터에 따라 chartRef.current?.legend?.legendItem와 useEffect로 legendItem 요소를 조정해주었다.)

공식 문서를 보면서 구현하고자 하는 바를 차트 라이브러리를 통해 이루어내는 건 좋은 경험이었고, 앞으로도 chart.js 라이브러리 활용과 관련된 포스팅을 하게 될 것 같다.

profile
25% Speciallist

0개의 댓글