Search code examples
reactjsdrag-and-drop

ReactJS when grabbing element around grid nodes are disapearing


I'm trying to move this gree node around my grid but when i move it last node in first line disapears.

Here is my code:

const onDrop = (e) => {
        e.preventDefault();
        console.log(e.target.id)
        let data = e.dataTransfer.getData("text");
        e.target.appendChild(document.getElementById(data));
    }

    const onDragStart = (e) => {
        e.dataTransfer.setData("text", e.target.id);
    }

    const onDragOver = (e) => {
        e.dataTransfer.setData("text", e.target.id);
    }

    return (
        <div
            onDrop={(e) => (onDrop(e))}
            onDragOver={(e) => (onDragOver(e))}
        >
            <div
                id={`${row}-${col}`}
                className={`node ${classes}`}
                draggable={draggAble}
                onDragStart={(e) => {
                    if (draggAble) {
                        onDragStart(e)
                    } else {
                        e.preventDefault()
                    }
                }}
            />
        </div>
    )

And this whole div is in another div with this code.

<div className="Grid" onDrop={(e) => (onDrop(e))} onDragOver={(e) => (onDragOver(e))}>

Here's link to my fiddle with snippet https://jsfiddle.net/Efiqqe/2tjs4v3f/1/

Each of this codes are in different components

Do you have any tips how to make the last node stop disapearing?

Thank you for your answers and I'm sorry if this post is not enough clear.


Solution

  • You move the child of 0-0 every time so you must add that in the first box.

    const div = document.createElement('div');
    div.id = 'temp-0-0';
    div.className = 'node';
    div.draggable = false;
    if(!document.getElementById('temp-0-0')) {
        document.getElementById('node-0-0').appendChild(div);
    }
    

    JSFiddle: https://jsfiddle.net/gupay0rc/2/