Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
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.

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda