Home > OS >  Vanilla JS Typerror: 'Cannot read properties of undefined (reading 'getBoundingClientRect&
Vanilla JS Typerror: 'Cannot read properties of undefined (reading 'getBoundingClientRect&

Time:10-21

Im trying to code a 2d game with javascript and I'm working on a position system in which if the user character overlaps the coin, a value changes. Im using .getBoundingClientRect() to get position and the function itself is fine. But anytime I add in an if statement that says if the function is true, (which it is), it gives me this error. Any ways to fix? (Attached code screenshots)

Code Chrome Console Error Image

CodePudding user response:

const handleScroll = () => {
      if(!ref.current) return
      if (ref.current.getBoundingClientRect().y <= -580 || null) 
  {
    console.log(ref.current.getBoundingClientRect().y);
    setSticky(true);
  } 
  else {
    setSticky(false);
  }
};

refs can be null on rerenders therefore always null check before accessing properties of elements refs. Here is what gaearon has to say about refs.

CodePudding user response:

The function elementsOverlap accepts 2 parameters, none of which you have provided while calling it.

And given that user is one of those parameters, the function will not use the user variable in the global scope. It will use the user parameter which is supposed to have been provided.

try removing the parameters since they're global anyway:

function elementOverlap(){
    // ... your code
}
  • Related