Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useRef / useEffect HTMLCanvasElement not assignable

I am fairly new to React and struggling to get a JS object to render through useRef and useEffect.

The JS render method is as follows:

import { Compass } from "steelseries";
const compass = new Compass(document.querySelector("#myCanvas"), {
  size: 200
});

Using a template for rendering a chart from chart.js I have tried to render this through React with typescript.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The react render method is as follows:

import { useCallback, useEffect, useRef } from "react"
import { observer } from "mobx-react"
import { Compass } from "steelseries"

type GaugeIndicatorProps = {
      value: 200
    }

export const Gauge = observer(({ value }: GaugeIndicatorProps) => {
      const canvasEl = useRef() as React.MutableRefObject<HTMLCanvasElement>
      const chartRef = useRef<Compass | null>()
      
      const createChart = useCallback(() => {
        const chartCanvas = canvasEl.current.getContext("2d")
        if (!chartCanvas) {
          return
        }
        chartRef.current = new Compass(chartCanvas, value)
      }, [value])

      useEffect(() => {
        if (!chartRef.current) {
          createChart()
        }
      }, [createChart])
    
      return (
        <div className={`canvas`}>
          <canvas className="top-chart" ref={canvasEl} />
        </div>
      )
    })

Not sure how to get this to render, because the compass object wants a Canvas | String | HTMLCanvasElement, which i have tried to pass to it using React.MutableRefObject and a getcontext("2d"), yet it is saying the following error for chartCanvas on this line of Code:
chartRef.current = new Compass(chartCanvas, value)

Argument of type ‘CanvasRenderingContext2D’ is not assignable to parameter of type ‘string | HTMLCanvasElement’.
Type ‘CanvasRenderingContext2D’ is missing the following properties from type ‘HTMLCanvasElement’: hieght etc

Sorry if this is a newbie question.

Thanks for your support.

Christopher

>Solution :

You have to pass the canvas itself, not its context. Use :

chartRef.current = new Compass(canvasEl.current, value)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading