기존 값(loadWordRequest)을 재사용하면서 도넛 차트 만들기

개발공부·2023년 1월 9일
0
post-thumbnail

* 결과

1) type : easy 값을 넣는 경우

2) type: middle 값을 넣는 경우

3) type: advance 값을 넣는 경우

* 중요한 점

▶ 새로 데이터를 불러오지 않고 기존 데이터를 활용

▶ 단어들을 불러오는 loadWordRequest에서 각각의 숫자값들만 추출해서 도넛 데이터에 넣기

const { wordLists } = useSelector((state) => state.word);
//해당 값들을 차트에 넣기
const easyLength = wordLists.filter((d) => d.type === "easy").length;
const middleLength = wordLists.filter((d) => d.type === "middle").length;
const advanceLength = wordLists.filter((d) => d.type === "advance").length;

import WordChart from "./WordChart";

//길이 값들 중 하나라도 0이 아니거나 로그인이 되어 있을 경우에 차트(도넛)가 보여짐
  {(easyLength !== 0 || middleLength !== 0 || advanceLength !== 0) &&
        UserId && (
          <div className="flex justify-center relative bottom-10">
            <WordChart
              easyLength={easyLength}
              middleLength={middleLength}
              advanceLength={advanceLength}
            />
          </div>
        )}

* 차트 도넛 만들기

유튜브 강의(chart.js)

[componenets/WordChart.js]

import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";

ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);

const WordChart = ({ easyLength, middleLength, advanceLength }) => {
  const data = {
    labels: ["Easy", "Middle", "Advance"],
    datasets: [
      {
        label: "Poll",
        data: [easyLength, middleLength, advanceLength],
        backgroundColor: [
          "rgba(240, 187, 98, 0.5)",
          "rgba(78, 108, 80, 0.5)",
          "rgb(255, 99, 71, 0.5)",
        ],
        borderColor: [
          "rgba(240, 187, 98, 0.5)",
          "rgba(78, 108, 80, 0.5)",
          "rgb(255, 99, 71, 0.5)",
        ],
        datalabels: {
          // This code is used to display data values
          formatter: function (value, context) {
            var idx = context.dataIndex;
            if (easyLength < 0 || middleLength < 0 || advanceLength < 0) {
              return idx;
            }
            if (easyLength > 0 && middleLength > 0 && advanceLength > 0) {
              return context.chart.data.labels[idx] + " : " + value;
            }
          },
          font: {
            weight: "bold",
            size: 16,
          },
        },
      },
    ],
  };

  const options = {
    plugins: {
      legend: {
        position: "bottom",
        align: "center",
      },
    },
  };

  return (
    <div className="w-60 h-60 grid grid-cols-2 gap-4 place-content-center">
      <Doughnut data={data} options={options}></Doughnut>
    </div>
  );
};

export default WordChart;
profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글