오픈소스 라이브러리인 apexcharts로 차트를 간단하게 구현할 수 있다!

참고 - 코인이름 값 가져오기

/{코인이름}에서 /{코인이름}/chart 주소로 이동할 때 {코인이름} 값 받아오는 방법

1. useParams - 주소에 있는 값 가져오기
// Chart.tsx
import { useParams } from "react-router-dom";

function Chart() {
  const params = useParams();
  console.log(params);
  return <h1>Chart</h1>;
}

export default Chart;
2. props로 받아서 사용하기
// Chart.tsx
interface ChartProps {
  coinId: string;
}

function Chart({ coinId }: ChartProps) {
  console.log(coinId);
  return <h1>Chart</h1>;
}

export default Chart;

 

Chart 그리기

ApexChart.js DEMOs

 

JavaScript Chart Examples & Samples Demo – ApexCharts.js

Get a glimpse of ApexCharts by exploring all the samples created using the library. You can download these JavaScript Chart Examples and use them freely.

apexcharts.com

설치
npm install --save react-apexcharts apexcharts
차트적용
// Chart.tsx
import ApexChart from "react-apexcharts";

interface ChartProps {
  coinId: string;
}

function Chart({ coinId }: ChartProps) {
  return (
    <div>
      <ApexChart
        type="line"
        series={[
          { name: "potato", data: [1, 2, 3, 4, 5, 6] },
          { name: "tomato", data: [12, 5, 3, 23, 16, 17] },
        ]}
        options={{ chart: { height: 500, width: 500 } }}
      />
    </div>
  );
}

export default Chart;
데이터로 차트 그리기
// Chart.tsx
import { useQuery } from "react-query";
import { fetchCoinHistory } from "../api";
import ApexChart from "react-apexcharts";

interface ChartProps {
  coinId: string;
}

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

function Chart({ coinId }: ChartProps) {
  const { isLoading, data } = useQuery<IPriceHis[]>(["priceHis", coinId], () =>
    fetchCoinHistory(coinId)
  );
  return (
    <div>
      {isLoading ? (
        "Loading Chart"
      ) : (
        <ApexChart
          type="line"
          series={[
            {
              name: `${coinId}`,
              data: data?.map((price) => parseFloat(price.close)) ?? [],
            },
          ]}
          options={{
            chart: {
              height: 500,
              width: 500,
              toolbar: { show: false },
              background: "transparent",
            },
            grid: {
              show: true,
              borderColor: "#90A4AE",
            },
            stroke: { curve: "smooth", width: 2, colors: ["#ff4757"] },
            xaxis: { floating: true },
            yaxis: {
              labels: {
                formatter(val, opts) {
                  return val.toFixed(4);
                },
              },
            },
          }}
        />
      )}
    </div>
  );
}

export default Chart;

+ Recent posts