Bill
Bill

Reputation: 5150

TypeScript: 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'

I'm trying to useRef to get a refenrece to the canvas but typescript is complaining

import React, { useRef } from 'react';
const AddPhoto: React.FC = () => {
  const canvas = useRef<HTMLCanvasElement>(null);
  const ctx: CanvasRenderingContext2D = canvas.getContext('2d')!;
//                                                 ^ error
}
  return (
      <canvas
          ref={canvas}
          width={315}
          height={315}
     />
)

The error I get is

Property 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'.ts(2339)

if I change it to

    if (canvas && canvas.current) {
      const ctx: CanvasRenderingContext2D = canvas.current.getContext('2d');
//           ^error

    }

the error is now

Type 'CanvasRenderingContext2D | null' is not assignable to type 'CanvasRenderingContext2D'.
  Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)

Upvotes: 1

Views: 3304

Answers (1)

boikevich
boikevich

Reputation: 408

As you use useRef, your value stores not just in canvas variable, but in canvas.current, so you should use canvas.current.getContext('2d').


To fix type problem, use this instead of if(...){...}

const ctx: CanvasRenderingContext2D | null = canvas.current ? canvas.current.getContext('2d') : null;

Upvotes: 3

Related Questions