artus9033 / chartjs-plugin-dragdata

Draggable data points plugin for Chart.js
MIT License
257 stars 55 forks source link

Drag is not working in any chart #122

Closed gauravsharma-fareye closed 1 year ago

gauravsharma-fareye commented 1 year ago

Describe the bug Hey, I am trying to create a radar chart where I can drag the nodes. The chart is getting populated but drag is not working. I looked at all solutions but nothing is working. Same code is working in fiddle but not in my machine. The code i am adding is line chart code.

import React, { useState, useContext, useRef, useCallback } from 'react';
import { Chart as ChartJS, registerables } from "chart.js";
import { Line } from "react-chartjs-2";

import "chartjs-plugin-dragdata";

ChartJS.register(...registerables);

export default function App() {
  const initSeries = [1, 3.5, 5, 2.8];
  const [series, setSeries] = useState(initSeries);
  const stateRef = useRef();

  stateRef.current = series;

  const options = {
    responsive: true,
    dragData: true,
    plugins: {
      legend: {
        position: "top"
      },
      title: {
        display: true,
        text: "Chart.js Line Chart"
      },

      dragData: {
        round: 2,
        showTooltip: false,
        onDragStart: (e, datasetIndex, index, value) => {
          if (index === 0 || index === series.length - 1) {
            console.log("First or last datapoint can't drag");
            return false;
          }
        },
        onDrag: (e, datasetIndex, index, value) => {
          console.log(stateRef.current);
          console.log("onDrag series: ", stateRef.current[index]);
          if (
            value < stateRef.current[index] - 0.5 ||
            value > stateRef.current[index] + 0.5
          ) {
            return false;
          }
        },
        onDragEnd: (e, datasetIndex, index, value) => {
          setSeries((arr) =>
            arr.map((x, xIndex) => (xIndex === index ? value : x))
          );
        }
      }
    }
  };

  const data = {
    labels: ["2020", "2021", "2022", "2023"],
    datasets: [
      {
        label: "alex",
        data: JSON.parse(JSON.stringify(series)),
        borderColor: "rgb(255, 99, 132)",
        backgroundColor: "rgba(255, 99, 132, 0.5)"
      }
    ]
  };

  console.log("component Series: ", series);
  return (
    <>
      <Line height={200} width={400} data={data} options={options} />(
      <div className="grid-container">
        {series?.map((x, xIndex) => (
          <div className="grid-item" key={xIndex}>
            {x}
          </div>
        ))}
      </div>
      )
    </>
  );
}

"chart.js": "3.9.1", "chartjs-plugin-dragdata": "^2.2.5", "react": "^16.8.6", "react-chartjs-2": "^4.3.1",

Expected behavior Drag functionality should be working

gauravsharma-fareye commented 1 year ago

This issue is resolved by upgrading react version 18.2.0