Im using gsap
Draggable with reactjs
ES6
, I create new draggable like this in react component componentDidUpdate
lifecycle method
import React, { Component } from 'react'
import Draggable from 'gsap/Draggable'
class DraggableContainer extends Component {
render(){
...
}
componentDidUpdate(){
const draggable = Draggable.create('.box', {
onPress: ()=>{
// currentElement suppost to contain dom element of clicked, but its undefined because 'this' is 'DraggableContainer'
const currentElement = this.target
}
})
}
}
inside method body of onPress
this.target should give current element but its undefined and this
is wrong context.
How can i access current elent inside this method?
You are using arrow function
, it will automatically bind
the context of that object
which will call that method. To access the target element use event object
.
In JavaScript, the thing called this, is the object that "owns" the JavaScript code. The value of this, when used in a function, is the object that "owns" the function.
Write it like this to access the target element:
const draggable = Dragable.create('.box', {
...,
onPress:(e) => {
//now this.target is wrong
const el = e.target;
}
})
Check this answer for more details about this keyword.