Search code examples
reactjsfunctionthistypeerrorgsap

Typeerror: this.checkPositions is not a function React


So I have this little bit of code in my react app that makes my app crash:

updateCenterElem() {
let elems = document.elementsFromPoint(winMidX, winMidY);
elems.forEach(elem => {
  if(elem.matches(imageSelector) && !lastCenteredElem.isSameNode(elem)) {
    lastCenteredElem = elem; 

    this.checkPositions(lastCenteredElem);
  }
});
}

Then I got the following error: typeerror: this.checkPositions is not a function. I'm guessing I'm loosing this at some point And I've tried many things like binding 'this' or declaring a variable like self = this but nothing works.

Edit it is called inside this function:

createDraggable() {
 let options = {
trigger: ".mask",
dragResistance: 0.4,
resistance: 400,
onDrag: this.updateCenterElem,
}

if(useInertia) {
options.inertia = true;
options.onThrowUpdate = this.updateCenterElem;

if(useCenterGrid) {
  options.onThrowComplete = centerGrid;
}
} else if(useCenterGrid) { // No inertia
options.onDragEnd = centerGrid;
}

return Draggable.create(containerSelector, options);
}

I'm using gsap by the way

Do you have an idea how I could resolve my problem ? Thank you


Solution

  • How do you use updateCenterElem ? If it's event handler or etc. your method declaration should look like this:

    updateCenterElem = () => {
    let elems = document.elementsFromPoint(winMidX, winMidY);
    

    Or you should bind context when setting handler

    ...={this.updateCenterElem.bind(this)}