Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef syntax in React

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading