개발/🟦 React

🟦 [React] Chart.js 라이브러리 설치 x , cdn 사용

비니_ 2025. 3. 9. 11:03
728x90

✔️ 일반 html로 차트 꾸리기

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
      .dashboard {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        padding: 20px;
      }

      .chart_box {
        padding: 20px;
        border-radius: 12px;
        background: #292b3d;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        transition: transform 0.2s ease-in-out;
      }

      .chart_box:hover {
        transform: scale(1.05);
      }

      canvas {
        width: 100% !important;
        height: 250px !important;
      }
    </style>
  </head>
  <body>
    <h2>Chart.js 대시보드</h2>
    <div class="dashboard">
      <div class="chart_box"><canvas id="barChart"></canvas></div>
      <div class="chart_box"><canvas id="lineChart"></canvas></div>
      <div class="chart_box"><canvas id="pieChart"></canvas></div>
      <div class="chart_box"><canvas id="doughnutChart"></canvas></div>
      <div class="chart_box"><canvas id="radarChart"></canvas></div>
      <div class="chart_box"><canvas id="scatterChart"></canvas></div>
    </div>

    <script>
      document.addEventListener("DOMContentLoaded", function () {
        //DOMContentLoaded : useEffect와 같음

        const labels = ["1월", "2월", "3월", "4월", "5월", "6월"];
        const dataValues = [65, 95, 30, 20, 50, 67];

        // barChart
        new Chart(document.getElementById("barChart"), {
          type: "bar",
          data: {
            labels: labels,
            datasets: [
              {
                label: "월별 판매량",
                data: dataValues,
                backgroundColor: "rgba(0, 192, 255, 0.8)",
                borderColor: "rgba(0, 192, 255, 1)",
                borderWidth: 2,
              },
            ],
          },
          options: { responsive: true },
        });

        // lineChart
        new Chart(document.getElementById("lineChart"), {
          type: "line",
          data: {
            labels: labels,
            datasets: [
              {
                label: "매출 변화",
                data: dataValues,
                borderColor: "#ff6384",
                borderWidth: 3,
                fill: false,
              },
            ],
          },
          options: { responsive: true },
        });

        // pieChart
        new Chart(document.getElementById("pieChart"), {
          type: "pie",
          data: {
            labels: ["A제품", "B제품", "C제품"],
            datasets: [
              {
                data: [30, 45, 25],
                backgroundColor: ["#ff6384", "#fff", "#d2d2d2"],
              },
            ],
          },
          options: { responsive: true },
        });

        // doughnutChart
        new Chart(document.getElementById("doughnutChart"), {
          type: "doughnut",
          data: {
            labels: ["서울", "부산", "대구", "여수"],
            datasets: [
              {
                data: [30, 45, 15, 10],
                backgroundColor: ["#ff6384", "#fff", "#d2d2d2", "#222"],
              },
            ],
          },
          options: { responsive: true },
        });

        // radarChart
        new Chart(document.getElementById("radarChart"), {
          type: "radar",
          data: {
            labels: ["기술력", "디자인", "마켓팅", "가격", "서비스"],
            datasets: [
              {
                label: "제품 평가",
                data: [80, 45, 15, 85, 100],
                borderColor: "#36a2db",
                backgroundColor: "rgba(54, 162, 235, 0.3)",
              },
            ],
          },
          options: { responsive: true },
        });

        // scatterChart
        new Chart(document.getElementById("scatterChart"), {
          type: "scatter",
          data: {
            datasets: [
              {
                label: "산점도 데이터",
                data: [
                  { x: 10, y: 20 },
                  { x: 20, y: 52 },
                  { x: 15, y: 20 },
                  { x: 85, y: 50 },
                  { x: 90, y: 80 },
                ],
                backgroundColor: "#36a2db",
              },
            ],
          },
          options: { responsive: true },
        });
      });
    </script>
  </body>
</html>

 

 

리액트로 바꿔보기

 

✔️  라이브러리 설치 안하고 cdn으로!

 

- Dashboard.jsx 컴포넌트 파일

import React, { useDebugValue, useEffect, useRef } from "react";
import "./Dashboard.css";
import "https://cdn.jsdelivr.net/npm/chart.js";

// 차트 그리기
const ChartComponent = ({ type, data, options }) => {
    const canvasRef = useRef(null); // canvas 생성
    const chartRef = useRef(null); // 차트 중복 방지

    useEffect(() => {
        if(!canvasRef.current) return; // cansvasRef 객체가 없으면 함수 종료
        
        if(chartRef.current){ // canvasRef 객체가 있으면 기존 차트 삭제하고 초기화
            chartRef.current.destroy();
            chartRef.current = null;
        }        
        
        const ctx = canvasRef.current.getContext("2d"); // 캔버스 컨텍스트 가져오기
        chartRef.current = new Chart(ctx, { // 차트 생성
            type,
            data,
            options,
        })


    }, [type, data, options]);

    return (
        <div className="chart-box"><canvas ref={canvasRef}></canvas></div>
    )
};

const Dashboard = () => {
    const labels = ["1월", "2월", "3월", "4월", "5월", "6월"];
    const dataValues = [65, 95, 30, 20, 50, 67];
    const optionValue = {responsive: true};

    // barChart
    const barChartData = {
        labels: labels,
        datasets: [
            {
                label: "월별 판매량",
                data: dataValues,
                backgroundColor: "rgba(0, 192, 255, 0.8)",
                borderColor: "rgba(0, 192, 255, 1)",
                borderWidth: 2,
            },
        ],
        options: optionValue,
    };

    // lineChart
    const lineChartData = {
        labels: labels,
        datasets: [
            {
                label: "매출 변화",
                data: dataValues,
                borderColor: "#ff6384",
                borderWidth: 3,
                fill: false,
            },
        ],
        options: optionValue,
    };

    // pieChart
    const pieChartData = {
        labels: ["A제품", "B제품", "C제품"],
        datasets: [
            {
                data: [30, 45, 25],
                backgroundColor: ["#ff6384", "#fff", "#d2d2d2"],
            },
        ],
        options: optionValue,
    };

    // doughnutChart
    const doughnutChartData = {
        labels: ["서울", "부산", "대구", "여수"],
        datasets: [
            {
                data: [30, 45, 15, 10],
                backgroundColor: ["#ff6384", "#fff", "#d2d2d2", "#222"],
            },
        ],  
    };

    // radarChart
    const radarChartData = {
        labels: ["기술력", "디자인", "마켓팅", "가격", "서비스"],
        datasets: [
            {
                label: "제품 평가",
                data: [80, 45, 15, 85, 100],
                borderColor: "#36a2db",
                backgroundColor: "rgba(54, 162, 235, 0.3)",
            },
        ],
    };

    // scatterChart
    const scatterChartData = {
        labels: ["기술력", "디자인", "마켓팅", "가격", "서비스"],
        datasets: [
            {
                label: "산점도 데이터",
                data: [
                  { x: 10, y: 20 },
                  { x: 20, y: 52 },
                  { x: 15, y: 20 },
                  { x: 85, y: 50 },
                  { x: 90, y: 80 },
                ],
                backgroundColor: "#36a2db",
            },
        ],
    };

    return (
        <div className="dashboard">
            <ChartComponent type="bar" data={barChartData} options={optionValue} />
            <ChartComponent type="line" data={lineChartData} options={optionValue} />
            <ChartComponent type="pie" data={pieChartData} options={optionValue} />
            <ChartComponent type="doughnut" data={doughnutChartData} options={optionValue} />
            <ChartComponent type="radar" data={radarChartData} options={optionValue} />
            <ChartComponent type="scatter" data={scatterChartData} options={optionValue} />
        </div>
    )
};

export default Dashboard;

 

- App.jsx 파일

import './App.css'
import Dashboard from './Dashboard'

function App() {

  return (
    <>
      <h2>React Dashboard</h2>
      <Dashboard />
    </>
  )
}

export default App



 

결과 화면👇

 

728x90