I was trying to create a canvas element with some basic shapes, using React hooks and Typescript, but I'm running into an error where the context in useEffect() could be null (ts2531).
I'm assuming this is because my canvasRef is null by default, but I'm a bit unsure what else I can set it to, or if there is a better way to go about this?
Here is my code so far (edit, solution below):
import React, { useRef, useEffect } from 'react';
interface CanvasProps {
width: number;
height: number;
}
const Canvas = ({ width, height }: CanvasProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
if (canvasRef.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
context.beginPath();
+ context.arc(50, 50, 50, 0, 2 * Math.PI);
+ context.fill();
}
},[]);
return <canvas ref={canvasRef} height={height} width={width} />;
};
Canvas.defaultProps = {
width: window.innerWidth,
height: window.innerHeight
};
export default Canvas;
Following Alex Wayne's speedy answer, here is my updated useEffect(), which works.
useEffect(() => {
if (canvasRef.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
if (context) {
context.beginPath();
context.arc(50, 50, 50, 0, 2 * Math.PI);
context.fill();
}
}
This is because getContext can return null. Docs : https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
If the contextType doesn't match a possible drawing context, null is returned.
Ensure it's not null e.g.
const context = canvas.getContext('2d');
if (context == null) throw new Error('Could not get context');
// now safe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With