Styling an element with JavaScript in react and typescript

Viewed 111

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>
        )
    }
}
1 Answers

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
Related