Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Canvas, with React hooks and Typescript [duplicate]

I was trying to create a canvas element with some basic shapes, using React hooks and Typescript, but I'm running into an error where the context in useEffect() could be null (ts2531).

I'm assuming this is because my canvasRef is null by default, but I'm a bit unsure what else I can set it to, or if there is a better way to go about this?

Here is my code so far (edit, solution below):

import React, { useRef, useEffect } from 'react';

interface CanvasProps {
    width: number;
    height: number;
}

const Canvas = ({ width, height }: CanvasProps) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);

    useEffect(() => {
        if (canvasRef.current) {
            const canvas = canvasRef.current;
            const context = canvas.getContext('2d');  
            context.beginPath();
+           context.arc(50, 50, 50, 0, 2 * Math.PI);
+           context.fill(); 
        }       
    },[]);

    return <canvas ref={canvasRef} height={height} width={width} />;
};

Canvas.defaultProps = {
    width: window.innerWidth,
    height: window.innerHeight
};

export default Canvas;

Following Alex Wayne's speedy answer, here is my updated useEffect(), which works.

    useEffect(() => {
    if (canvasRef.current) {
        const canvas = canvasRef.current;
        const context = canvas.getContext('2d');  
        if (context) {
            context.beginPath();
            context.arc(50, 50, 50, 0, 2 * Math.PI);
            context.fill(); 
        }

    }      
like image 949
David Alan Bruce Avatar asked Aug 30 '26 15:08

David Alan Bruce


1 Answers

This is because getContext can return null. Docs : https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext

If the contextType doesn't match a possible drawing context, null is returned.

Fix

Ensure it's not null e.g.

        const context = canvas.getContext('2d');  
        if (context == null) throw new Error('Could not get context');
        // now safe
like image 185
basarat Avatar answered Sep 02 '26 07:09

basarat