James
James

Reputation: 1485

React useRef is undefined

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

Upvotes: 18

Views: 55165

Answers (1)

Hamza El Aoutar
Hamza El Aoutar

Reputation: 5667

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)
},[])

Upvotes: 7

Related Questions