react-native-draggable
react-native-draggable copied to clipboard
useState Problem for Re-render
Hello, Thanks for this amazing library. It seems very useful who don't want to write their own Draggable component. However, I couldn't understand how we can get coordinates for the whole component. I'm trying to use the useState hook to get X and Y coordinates. When I use it inside onDrag, the Draggable stops moving in any direction. Could you help me with this problem please?
Thanks a lot.
@doganoruc you should use onDragRelease instead, take a look at the documentation and see what you can get from arguments passed to this callback
@doganoruc I just spent a lot of time trying to figure this out. I finally was able to get it to work but it was a little more complicated than I was expecting.
First, as @t4dek mentioned you need to set the new x and y in onDragRelease instead of onDrag. The new x and y positions can be calculated by:
x = event.nativeEvent.pageX - event.nativeEvent.locationX;
y = event.nativeEvent.pageY - event.nativeEvent.locationY;
event.nativeEvent.pageX/Y gives you the position of the draggable component within the screen, and event.nativeEevnt.locationX/Y gives you the position of the touch within the draggable component, thus the above calculation should give the exact position of the users touch on the screen.
Finally, when you manually set the x and y position of the draggable component it doesn't behave as expected (the movements seem to compound). Thus you need to sort of refresh the component by resetting the key for the draggable component. One way to do this is as mentioned in this issue:
Create first a state to hold this value which trigger the re-render of the entire Draggable.
const [reloader, setReloader] = React.useState<number>(Date.now());
Add the value as a key to your draggable.
<Draggable key={reloader} />
Set the state every time you want the entire object to be re-rendered, for example inside the function that you call in onDragRelease
setReloader(Date.now());
Hope this helps with your issue and anyone else who runs into the same problem!