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 ํ๊ฒฝ์์ ๋ฉํฐํ์ ์์๊ฐ ๋ณ๋ก ์์ด์ ์ด์ง ํด๋ฉจ๋๋ฐ์, ํน์ ์ ์ ๊ฐ์ ์ํฉ์ด์๋ผ๋ฉด, ์ ์์ค์ฝ๋๋ ํ๋ฒ ์ฐธ๊ณ ํด๋ณด์ธ์ :)