본문 바로가기

클라이언트/React
[리액트(React)] 차트(Chart) 사용하기

// 차트, Chart

- 데이터를 시각화해서 나타낸다.

- 많은 js 라이브러리들이 존재한다.


// ApexCharts.js

- 공식 문서:  https://apexcharts.com/docs/react-charts/

 

React-ApexChart - A React Chart wrapper for ApexCharts.js

Create React Charts using a React Chart component for ApexCharts. Build beautiful and interactive visualizations in your react applications.

apexcharts.com


1. 설치

npm install --save react-apexcharts apexcharts

2. 사용

import ApexChart from 'react-apexcharts';

<ApexChart
          type=""
          series={[
            {
              name: '그래프명1',
              data: [값 배열1],
            },
            {
              name: '그래프명2',
              data: [값 배열2],
            },
                 ...
          ]}
          options={{ 옵션들   }}
        />

import { useOutletContext } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { fetchCoinHistory } from '../api';
import ApexChart from 'react-apexcharts';

interface IHistorical {
  time_open: number;
  time_close: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  market_cap: number;
}

function Chart() {
  const coinId = useOutletContext<string>();
  const { data, isLoading } = useQuery<IHistorical[]>({
    queryKey: ['ohlcv', coinId],
    queryFn: () => fetchCoinHistory(coinId),
  });

  return (
    <div>
      {isLoading ? (
        'Loading chart...'
      ) : (
        <ApexChart
          type="line"
          series={[
            {
              name: 'sales',
              data: data?.map((price) => Number(price.close))!,
            },
          ]}
          options={{
            theme: {
              mode: 'dark',
            },
            chart: {
              height: 300,
              width: 500,
              toolbar: {
                show: false,
              },
              background: 'transparent',
            },
            grid: {
              show: false,
            },
            stroke: {
              curve: 'smooth',
              width: 4,
            },
            yaxis: {
              show: false,
            },
            xaxis: {
              axisBorder: { show: false },
              axisTicks: { show: false },
              labels: { show: false, datetimeFormatter: { month: "mm 'yy" } },
              type: 'datetime',
              categories: data?.map((price) =>
                new Date(price.time_close * 1000).toUTCString(),
              ),
            },
            fill: {
              type: 'gradient',
              gradient: {
                gradientToColors: ['#0be881'],
                stops: [0, 100],
              },
            },
            colors: ['#0fbcf9'],
            tooltip: {
              y: {
                formatter: (value) => `$${value.toFixed(2)}`,
              },
            },
          }}
        />
      )}
    </div>
  );
}

export default Chart;