How to get the position of a moving element in React Native

Viewed 74

I am currently trying to develop an app with draggable elements using React Native and the library react Native draggable (https://www.npmjs.com/package/react-native-draggable).

My goal is to get the position of my Draggable element. (So I can change their color depending on where it is on the screen).

I tried different method but nothing worked for me. Here is the last thing I tried :

return (
    <View>
      <Draggable 
        onDragRelease={event =>
        {const layout = event.nativeEvent.layout;
          console.log('x:', layout.x);
          console.log('y:', layout.y);
        }
        }
        x={positionX} 
        y={positionY} 
        renderSize={56} 
        renderColor='#BDFF00' 
        renderText={'Drag me'} 
        // onDrag={getPosition}
        /> 
    </View>
  )

The code above returns this error (TypeError: undefined is not an object (evaluating 'layout.x'))

I also tried to do this :

  const getPosition = (event) => {
    console.log(event.locationX)
    setPositionX(event.locationX)
    setPositionY(event.locationY)
  };

  const changerColorFunction = () => {
  
  }

  return (
    <View>
      <Draggable 
        x={positionX} 
        y={positionY} 
        renderSize={56} 
        renderColor='#BDFF00' 
        renderText={'Drag me'} 
        onDrag={getPosition}
        /> 
    </View>
  )

Based on the react native Draggable documentation, but it is not working too. I think, I didn't fully understand how it should be working. Any help would be great.

0 Answers
Related