[error] 드롭박스 눌러도 이름이 바뀌지 않음. 데이터는 바뀜

유진·2023년 11월 1일
0

23.11.01.(화)


오류

  • SelectBox에 있는 return문은 React에서 onChange할 때마다 인식해야하는데 그것 못했다. 그래서 데이터는 바뀌는데 드롭박스 이름은 연동이 안 된다.

오류 해결

  • useEffect를 이용했다.
  useEffect(() =>{},[currentData])
  • SelectBox에 있던 내용을 OverTime.jsx return에 넣어주었다.
  • 주석처리해서 없애고, props.options.map((option, index) -> OPTIONS.map((option, index)으로 바꿨다.
<div>잔업률_
            {/* <SelectBox options={OPTIONS}/> */}
            <select onChange={handleChange}>
        {OPTIONS.map((option, index) => (
          <option
            key={index}
            value={option.value}
            // defaultValue={props.defaultValue === option.value}
          >
            {option.name}
          </option>
        ))}
      </select>
            </div>

import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Tooltip,  } from "chart.js";
import React, {useEffect, useState} from 'react'
import styles from "./OverTime.module.scss";
import { Bar } from 'react-chartjs-2'

ChartJS.register(BarElement, CategoryScale, LinearScale, Tooltip, Legend);
function OverTime() {
  const barOption = {
    // (width / height)크기를 조정할 때 원래 캔버스 종횡비를 유지 유무
    maintainAspectRatio: false,

    // 컨테이너가 수행할 때 차트 캔버스의 크기를 조정
    responsive: true,

    // bar chart
    plugins: {
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Bar Chart Example'
        },
        tooltip: {
            mode: 'index',
            intersect: false,
        },
        datalabels: {
            color: '#fff',
            align: 'end',
            anchor: 'end',
            offset: 5,
            display: function(context) {
                return context.dataset.data[context.dataIndex] !== 0; 
            },
            formatter: function(value) {
                return value;
            },
            font: {
              size: "14px",
              weight: "bold",
            },  
        }
    }
  }
  
  //잔업률 전체 데이터
  const barDataTotal = {
    labels: ['년', '월'],
    datasets: [
      {
        color: "#fff",
        label: "잔업률",
        data: [60, 30],
        backgroundColor: ["rgba(54, 162, 235, 1)"],
        borderColor: ["rgba(54, 162, 235, 1)"],
        borderWidth: 1,
      },
    ]
  }
  // 잔업률 4직 1조 데이터
  const barDataFirst = {
    labels: ['년', '월'],
    datasets: [
      {
        color: "#fff",
        label: "잔업률",
        data: [30, 20],
        backgroundColor: ["rgba(54, 162, 235, 1)"],
        borderColor: ["rgba(54, 162, 235, 1)"],
        borderWidth: 1,
      },
    ]
  }
  // 잔업률 4직 2조 데이터
  const barDataSecond = {
    labels: ['년', '월'],
    datasets: [
      {
        color: "#fff",
        label: "잔업률",
        data: [10, 0],
        backgroundColor: ["rgba(54, 162, 235, 1)"],
        borderColor: ["rgba(54, 162, 235, 1)"],
        borderWidth: 1,
      },
    ]
  }

  // DropDown 메뉴 바뀔 때마다 데이터 변경
  const [currentData, setCurrentData] = useState(barDataTotal)

  useEffect(() =>{},[currentData])
  const handleChange = (e) => {
    console.log(e.target.value)
      switch (e.target.value) {
        case '전체':
          setCurrentData(barDataTotal);
          break;
        case '4직 1조':
          setCurrentData(barDataFirst);
          break;
        default:
          setCurrentData(barDataSecond);
      }
    }  // DropDown 메뉴
  const OPTIONS = [
    {value: '전체', name: '전체'},
    {value: '4직 1조', name: '4직 1조'},
    {value: '4직 2조', name: '4직 2조'}
  ];
  
  return (
  <>
      <div className={[styles["over-time"]]}>
        <div className={[styles["head"]]}>
           <div>잔업률_
            <select onChange={handleChange}>
        {OPTIONS.map((option, index) => (
          <option
            key={index}
            value={option.value}
          >
            {option.name}
          </option>
        ))}
      </select>
            </div>
        </div>
        <div className={[styles["chart"]]} >
           <Bar type="bar" data={currentData} options={barOption}/>
        </div>
      </div>
  </>
  )
}

export default OverTime
profile
긍정 🍋🌻

0개의 댓글