1

I am unable to use the ref prop for the line chart and pie chart that I am working on.

I have tried to set different types for useRef and I am always getting the error

Type 'RefObject<Chart<keyof ChartTypeRegistry, (number | [number, number] | Point | BubbleDataPoint | null)[], unknown>>' is not assignable to type 'ForwardedRef<ChartJSOrUndefined<"pie", (number | [number, number] | Point | BubbleDataPoint | null)[], unknown>> | undefined'.

The following is the source code:-

import { useState,useRef, MouseEvent} from 'react';
declare const Data: { mark: unknown }[];
import {Chart, Line} from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { getElementAtEvent } from 'react-chartjs-2/dist/utils';


ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
)


export default function App() {
  const [chartData, setChartData] = useState({
    labels: Data.map(item => item.mark), 
    datasets: [
      {
        label: 'Marks',
        data: Data.map(item => item.mark),
        backgroundColor: '#2a71d0',
        borderColor: 'black',
        borderWidth: 2
      }
    ]
  });
  const chartRef = useRef<ChartJS>(null);

  const onclick = (e:MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      console.log(getElementAtEvent(chartRef.current,e))
    }
  }
  return (
    <div className='PerformanceChart'>
      <Line ref={chartRef} data={chartData} onClick={onclick}   />
    </div>
  );
}

1
  • Are <Line /> and <canvas /> the same? Commented Dec 27, 2022 at 14:23

3 Answers 3

2

You have to change the type of your useRef to ChartJS:

const chartRef = useRef<ChartJS>(null)
Sign up to request clarification or add additional context in comments.

3 Comments

I did that but i still cant use the getElementAtEvent() and I am getting the same error
^ @magicrap This answer is correct. Also, see lines 44–49 in this TS Playground: tsplay.dev/wgAo9m
@Farnam This doesn't seem to be working anymore
0

Farnam's solution no longer seems to work (see the error in https://tsplay.dev/wgAo9m) and I couldn't find this ChartJSOrUndefined type.

For me it worked to just add an additional undefined option to the useRef type:

useRef<ChartJS<"bar"> | undefined>(null);

Comments

0

The ref prop of <Line> expects a type of ChartJS<"line">, make sure your useRef is declared as such:

// No need to initialize to `null`; React's TS types will infer the resulting
// type to be `ChartJS<"line"> | undefined`.
const chartRef = useRef<ChartJS<"line">>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.