Skip to content

Instantly share code, notes, and snippets.

@parris
Last active November 15, 2018 03:15
Show Gist options
  • Save parris/dda613e3ae78f14eb2dc9fa0f4bfce3d to your computer and use it in GitHub Desktop.
Save parris/dda613e3ae78f14eb2dc9fa0f4bfce3d to your computer and use it in GitHub Desktop.
Drag/Drop + Reparenting in React

React has fairly good support for most drag/drop scenarios except for the case where the dragged component will change parent elements. In that case, touchmove events will stop firing. Without React you'd normally just do something more imparative and just manually move an object around without destory it. In React you likely rely more on state/props to render your scenes; therefore, things become vaguely intractable. Even if your touchmove events are attached to document.body or window (etc) your touchmove event will still not fire.

I've read some discussions on the matter here:

  1. facebook/react#3965
  2. facebook/react#13113

Solution

I recently needed to address this in a codebase I work on. I just wanted to report some findings and success I had working around this particular issue. I found this workaround (and I have no idea why it works) https://stackoverflow.com/questions/33298828/touch-move-event-dont-fire-after-touch-start-target-is-removed

It shouldn't work from my understanding. But if you naively attach touchmove/touchend events directly to your event target (even if you know it is about to be removed from the DOM tree) touchmove and end fire as normal. I ended up stashing a reference to the old target on the component so I could later properly remove the event listener.

From my perspective, I think this should be a fine solution for the next year or two until some better option is invented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment