I was working on a basic project in React, and found this snippet of code which introduces useRef to take the reference of a canvas element. I am new to this and cannot figure out how this line works.
const canvasRef = (useRef < HTMLCanvasElement) | (null > null);
Any help or reference regarding this would be highly appreciated. The rest of the snippet for the canvas is below.
export interface ICanvasBoard {
height: number;
width: number;
}
const CanvasBoard = ({ height, width }: ICanvasBoard) => {
const canvasRef = (useRef < HTMLCanvasElement) | (null > null);
const [context, setContext] =
(useState < CanvasRenderingContext2D) | (null > null);
useEffect(() => {
//Draw on canvas each time
setContext(canvasRef.current && canvasRef.current.getContext("2d")); //store in state variable
}, [context]);
return (
<canvas
ref={canvasRef}
style={{
border: "3px solid black",
}}
height={height}
width={width}
/>
);
};
I have tried looking for the syntax as well as tried running this code. The useRef line does not seem to work.
>Solution :
The syntax is wrong. It should be like this:
const canvasRef = useRef<HTMLCanvasElement>(null);
Here we are declaring a ref called canvasRef and we tell TypeScript that this will refer to an HTMLCanvasElement using the type parameter (the thing in angle brackets). Refs to DOM elements are initialized with null.
The line declaring the context state is also wrong – it should be like this:
const [context, setContext] = useState<CanvasRenderingContext2D | null>(null);
Possibly some sort of auto-formatting could have printed the code like this.