Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useState Problem for Re-render #137

Open
doganoruc opened this issue Dec 9, 2022 · 2 comments
Open

useState Problem for Re-render #137

doganoruc opened this issue Dec 9, 2022 · 2 comments

Comments

@doganoruc
Copy link

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.

@t4dek
Copy link

t4dek commented Apr 6, 2023

@doganoruc you should use onDragRelease instead, take a look at the documentation and see what you can get from arguments passed to this callback

@Kojon74
Copy link

Kojon74 commented Oct 24, 2023

@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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants