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