0

I'm attempting to implement a simple drag and drop piece of functionality in my React app.

Currently, the functionality works great on desktop, using these three functions:

const [dragId, setDragId] = useState()
    const [array, setArray] = useState(jobsArray)

    const handleDragOver = (ev) => { ev.preventDefault() }

    const handleDrag = (ev) => {
        console.log(ev.currentTarget.id);
        
        setDragId(ev.currentTarget.id)
    }

    const handleDrop = (ev) => {

        // Find the items that I want to arrange
        const foundItem = array.find(job => job.title === dragId)
        const dragItem = array.find(job => job.title === ev.currentTarget.id)

        // Create a copy of the array, with the element removed
        const filteredArray = array.filter(job => foundItem.title !== job.title) 

        // Find the element position of the item that I want to push up
        const elementPosition = array.indexOf(dragItem)

        // Insert the item into the correct element
        const newArray = [...filteredArray.slice(0, elementPosition), foundItem, ...filteredArray.slice(elementPosition)]
        console.log(newArray);
        

        // Update the original array to be the new array
        setArray(newArray)

    }

I'm then applying these onto a 'draggable' div, like so:

<div className="dashboard-list width-100 flex-center" draggable onDragOver={onDragOver} onDragStart={onDragStart} onDrop={onDrop} onTouchStart={onDragStart} onTouchEnd={onDrop} onTouchMove={onDragOver} id={title}>
{ content } 
</div>

As you can see, I've added the same functions onto the appropriate touch events (I think) - but it's not working.

What am I doing wrong?

Jon Nicholson
  • 927
  • 1
  • 8
  • 29
  • Mobile devices tend to use touch gestures for scrolling as well – is scrolling disabled? [Possibly helpful discussion here](https://stackoverflow.com/a/43275544/21146235) – motto Apr 12 '23 at 12:26
  • I’ve debugged it a little - it’s because the drop event on touch isn’t passing in the correct currentTarget.id. It’s passing the element being touched, rather than the drop location. – Jon Nicholson Apr 12 '23 at 12:50
  • Okay, no easy solution for you then :-/ Realistically, there is a lot of work in addressing all the weird edge-cases in getting drag-and-drop working on touch devices. I'd go with the advice on [this previous question, for instance](https://stackoverflow.com/q/53530511/21146235) and investigate existing libraries. – motto Apr 12 '23 at 13:05

0 Answers0