18

I think I may be misusing useRef here. When I try to draw to the canvas I am getting the following error: cannot set 'fillStyle' of undefined.

import React, { useEffect, useRef } from "react";
import useWindowSize from "../hooks/useWindowSize";

export default function Player() {
  const canvasRef = useRef();
  const ctx = useRef();

  useEffect(() => {
    ctx.current = canvasRef.current.getContext("2d");
  }, []);
  ctx.current.fillStyle = "green";
  ctx.current.fillRect(20, 20, 150, 100);
  return (
    <React.Fragment>
      <div>Hello</div>
      <canvas ref={canvasRef} width="500" height="500" />
    </React.Fragment>
  );
}

2
  • what is ctx? your using useRef but never assigning that ref to anything? Commented Oct 21, 2019 at 22:15
  • Hi thanks for your comment I think I assign cnvRef.current.getContext(‘2d’) to ctx.current in useEffect function Commented Oct 21, 2019 at 22:21

1 Answer 1

7

The first time you are trying to access ctx.current, it's still undefined because the assignment inside this effect still didn't happen:

useEffect(()=>{
    ctx.current = canvasRef.current.getContext('2d')
},[])

This is because the effect is run after the rendering phase.

You need to do that inside useEffect instead:

useEffect(()=>{
    ctx.current = canvasRef.current.getContext('2d')
    ctx.current.fillStyle= "green"
    ctx.current.fillRect(20,20,150,100)
},[])
Sign up to request clarification or add additional context in comments.

1 Comment

@James, I updated my answer to better explain what's happening, I guess the mistake you were making is thinking that the effect run before the render phase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.