Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 554
James Avatar asked Oct 21 '19 22:10

James


1 Answers

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)
},[])
like image 183
Hamza El Aoutar Avatar answered Sep 29 '22 22:09

Hamza El Aoutar