Framework/React

[React] react + typescript ์—์„œ multitype ๋ฉ€ํ‹ฐํƒ€์ž… Chart.js ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 7. 17. 22:58
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” react + typescript ์—์„œ Chart.js ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

How to do 

์ œ ์ผ€์ด์Šค์˜ ๊ฒฝ์šฐ ๋ง‰๋Œ€(bar) ๊ทธ๋ž˜ํ”„์™€ ์„ (line) ๊ทธ๋ž˜ํ”„๋ฅผ ํ•จ๊ป˜ ๊ทธ๋ ค์ฃผ๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด ๋จผ์ € MutiTypeChart ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค. 

 

# MutiTypeChart Component

props๋กœ data, height, options ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ๋ฉ€ํ‹ฐํƒ€์ž… ์ฐจํŠธ๋ฅผ ์œ„ํ•ด์„œ๋Š” Chart Component  ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

import React from 'react'
import {
  BarController,
  BarElement,
  CategoryScale,
  Chart as ChartJS,
  ChartData,
  ChartOptions,
  ChartType,
  Legend,
  LinearScale,
  LineController,
  LineElement,
  PointElement,
  Tooltip
} from 'chart.js'
import { Chart } from 'react-chartjs-2'

ChartJS.register(LinearScale, CategoryScale, BarElement, PointElement, LineElement, Legend, Tooltip, LineController, BarController)

interface Props {
  data: ChartData<ChartType, number[], string>
  height: number
  options: ChartOptions<ChartType>
}

const MultiTypeChart = (props: Props) => {
  const { data, height, options } = props

  return (
      <Chart<ChartType> type='bar' data={data} options={options} height={height} />
  )
}

export default MultiTypeChart

 

# MyComponent

datasets ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค๊ณ , ChartDataset ํƒ€์ž…์„ chart.js ๋กœ๋ถ€ํ„ฐ import ํ•ฉ๋‹ˆ๋‹ค. ์ดํ›„ ์‚ฌ์šฉํ•˜๊ณ ์ž ํ•˜๋Š” chart type ์„ ๋ช…์‹œํ•ด์ค๋‹ˆ๋‹ค. ์ €๋Š” line, bar ์ฐจํŠธ๊ฐ€ ํ•„์š”ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์•„๋ž˜์™€ ๊ฐ™์ด ๊ตฌ์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค. 

import { ChartData, ChartDataset, ChartOptions } from 'chart.js'
import MultiTypeChart from './MultiTypeChart'


const MyComponent = ({ data, psType }: Props) => {
  const labels = data.map(item => item.label)

  const series1: number[] = []
  const series2: number[] = []
  const series3: number[] = []

  data.forEach(temp => {
      series1.push(temp.data1)
      series2.push(temp.data2)
      series3.push(temp.data3)
  })

  const datasets: ChartDataset<'line' | 'bar', number[]>[] = [
    {
      type: 'line',
      label: 'A',
      borderColor: 'white',
      data: series3
    },
    {
      type: 'bar',
      label: 'B',
      backgroundColor: 'red',
      data: series1
    }
    {
      type: 'bar',
      label: 'C',
      backgroundColor: 'blue'
      data: series1
    }
  ]

  const options: ChartOptions<'line' | 'bar'> = {
  	...
  }

  const chartData: ChartData<'line' | 'bar', number[], string> = {
    labels,
    datasets
  }

  return (
      <MultiTypeChart data={chartData} options={options}/>
  )
}

export default MyComponent

 

 

react + typescript ํ™˜๊ฒฝ์—์„œ ๋ฉ€ํ‹ฐํƒ€์ž… ์˜ˆ์‹œ๊ฐ€ ๋ณ„๋กœ ์—†์–ด์„œ ์‚ด์ง ํ•ด๋ฉจ๋Š”๋ฐ์š”, ํ˜น์‹œ ์ €์™€ ๊ฐ™์€ ์ƒํ™ฉ์ด์‹œ๋ผ๋ฉด, ์œ„ ์†Œ์Šค์ฝ”๋“œ๋„ ํ•œ๋ฒˆ ์ฐธ๊ณ ํ•ด๋ณด์„ธ์š” :)


https://react-chartjs-2.js.org/examples/multitype-chart/

๋ฐ˜์‘ํ˜•