front/react

[ React, Typescript ] ChartJs 사용하기

dev_popo 2024. 1. 8. 13:29

 

 

chart.js 라이브러리 적용 해보고, 샘플 코드를 공유한다.

 

현재까지 공유된 버전이다.

React를 지원하는데 Chart.js만 설치하는 게 아니고 react용 cahrt.js를 설치해줘야 한다

pnpm add chart.js react-chartjs-2

저렇게 설치를 해주고 난 후, 실제 사용하기위해서는

import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";

ChartJS.register(ArcElement, Tooltip, Legend);

<Doughnut data={...} />

위 작업이 필요하다. chart.js에서 사용하는 메서드를 가져온 후 react에서 사용할 수 있게 register 해줘야 한다.

내 버전은

 

 

 

 

 

적용 코드

 

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

    const data = {
        labels,
        datasets: [
            {
                type: 'line' as const,
                label: 'Dataset 1',
                borderColor: 'rgb(255, 99, 132)',
                borderWidth: 2,
                fill: false,
                data: [4, 4, 5, 6, 8, 10, 12],
            },
            {
                type: 'bar' as const,
                label: 'Dataset 2',
                borderWidth: 2,
                borderColor: 'white',
                backgroundColor: 'rgba(255, 99, 132, 0.5)',
                data: [1, 2, 3, 4, 5, 6, 7],   
            },
            {
                type: 'bar' as const,
                label: 'Dataset 3',
                borderWidth: 2,
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                data: [2, 3, 4, 5, 4, 7, 8],
            },
            {
                type: 'bar' as const,
                label: 'Dataset 4',
                borderWidth: 2,
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                data: [2, 3, 4, 5, 4, 7, 8],
            },
            {
                type: 'bar' as const,
                label: 'Dataset 5',
                borderWidth: 2,
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                data: [23, 33, 34, 35, 43, 7, 38],
            },
            {
                type: 'bar' as const,
                label: 'Dataset 6',
                borderWidth: 2,
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                data: [22, 23, 42, 25, 24, 72, 28],
            },
            {
                type: 'bar' as const,
                label: 'Dataset 7',
                borderWidth: 2,
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                data: [12, 13, 14, 15, 14, 17, 18],
            },
            {
                type: 'bar' as const,
                label: 'Dataset 8',
                borderWidth: 2,
                backgroundColor: 'rgba(53, 162, 235, 0.5)',
                data: [5, 10, 15, 20, 25, 30, 40],
            },
        ],
    }

    const options: ChartOptions = {
        plugins: {
            // 범례(맨 위 데이터라벨)
            legend: {
                labels: {
                    usePointStyle: true,
                    pointStyle: 'rectRounded',
                },
                /* 범례 표시 */
                // display: false,

                /* 범레 클릭시 데이터 삭제 비활성화 */
                // onClick: false,

                position: 'bottom',
            },
            // 도넛차트 내부 데이터 표시
            datalabels: { display: false },
            tooltip: {
                callbacks: {
                    title(tooltipItem) {
                        // 툴팁의 제목 부분에 표시할 내용
                        return data.labels[tooltipItem[0].dataIndex]
                    },
                    label(tooltipItem) {
                        // 툴팁의 내용 부분에 표시할 내용
                        const dataset = data.datasets[tooltipItem.datasetIndex]
                        const label = dataset.label || ''
                        const value = tooltipItem.formattedValue
                        // label: value 형식으로 표시 (이중툴팁)
                        return [`${label}: ${value}`, `QTY: ${dataset.subData[0]}`]
                    },
                },
            },
        },
        scales: {
            x: {
                // 스택. 데이터를 개별로 두지 않고 쌓아 올림.
                stacked: true,
            },
            y: {
                // 값이 0보다 적더라도 시작을 0부터
                beginAtZero: true,
                stacked: true,
            },
        },
        onClick: (event: ChartEvent, elements: InteractionItem[]) => {
            if (elements[0] === undefined) return

            const dataIndex = elements[0].index
            if (dataIndex) setShowTable(true)
            else setShowTable(false)
            logger.debug(`Label: ${data.labels[dataIndex]}, Value: ${data.datasets[0].data[dataIndex]}`)
        },
    }

 

    return (
        <>
            <Chart type="bar" /* ref={chartRef} onClick={onClick} */ options={options} data={data} />
        </>
    )
}

 

이렇게 설정하면

화면엔 이렇게 나온다.

생각보다 간단!

options들만 여러가지 적용할 수 있고 자유도가 높으니 찾아보고 적용해보면 좋을듯하다.