1

I am trying to add some js to a canvas but i get an error saying the following. Please bear with me, i am a couple of hours into TS and have done one hobby project in react:

Object is possibly 'null'.ts(2531)

This is the object which might be null:

(property) React.RefObject<HTMLCanvasElement>.current: HTMLCanvasElement | null

This is the react that's not working as i want it to. From my understanding the ref element is like an id in HTML5 so referencing the JSX element at that node should allow me to add styling via Js?

import React from 'react';

export class LowerCanvas extends React.Component{
    canvas: React.RefObject<HTMLCanvasElement>

    constructor(props : any){
        super(props)
        this.canvas = React.createRef()
    }

    componentDidMount(){

        this.canvas.current.style.width = '500';
     /*canvas.style.height = '500';
     if (canvas.getContext) {
       const ctx = canvas.getContext('2d');
       ctx.rect(20, 50, 100, 100);
       ctx.shadowColor = 'gray';
       ctx.shadowBlur = 10;
       ctx.shadowOffsetX = 10;
       ctx.shadowOffsetY = 10;
       ctx.fillStyle = "red";
       ctx.fill();
     }*/

    }

    render(){
        return(
            <div style={{"height":"500px","width":"50vw","position":"absolute"}}>
                <canvas ref={this.canvas} width="100%" height="100%">

                </canvas>
            </div>
        )
    }
}
0

1 Answer 1

1

TypeScript is warning you that the this.canvas ref may not necessarily exist in the DOM yet, so calling methods on it may throw errors. TypeScript can't tell if the component has mounted yet either. You have to tell TypeScript that the value definitely exists at the point that you try to access it. Change:

componentDidMount(){
    this.canvas.current.style.width = '500';
    // other references to this.canvas.current

to

componentDidMount(){
    const canvas = this.canvas.current!
    canvas.style.width = '500';
    // other references to canvas
Sign up to request clarification or add additional context in comments.

2 Comments

What is the name of the ! operator in TS?
That's the non-null assertion operator typescriptlang.org/docs/handbook/release-notes/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.