Home > OS >  React useRef / useEffect HTMLCanvasElement not assignable
React useRef / useEffect HTMLCanvasElement not assignable

Time:12-14

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.

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

CodePudding user response:

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

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

  • Related