in drop function data value is getting empty ,so how to fix that if I want to drag and drop a div to a particular container. instead of getting the id its not fetching any value so its throws an error "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"
import { useState, useEffect } from "react";
export default function App() {
const [isDown, setIsDown] = useState(false);
const drag = document.querySelector(".drag");
const onm ousedown = () => {
setIsDown(true);
};
const onm ouseup = () => {
setIsDown(true);
};
const onm ousemove = (e) => {
console.log(e.clientX);
if (isDown) {
drag.style.top = e.clientY "px";
drag.style.left = e.clientX "px";
}
};
function dragi(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
ev.stopPropagation();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
function onDragOver(e) {
e.preventDefault();
}
return (
<div className="App">
<div
style={{
width: "350px",
height: "70px",
padding: "10px",
border: "1px solid #aaaaaa"
}}
id="div1"
onDrop={(event) => drop(event)}
onDragOver={onDragOver}
></div>
<div
className="drag"
onm ouseDown={(e) => onm ousedown(e)}
onm ouseUp={(e) => onm ouseup(e)}
onm ouseMove={(e) => onm ousemove(e)}
style={{
width: "50px",
height: "50px",
background: "yellow"
}}
draggable="true"
onDragStart={(event) => dragi(event)}
>
Drag
</div>
</div>
);
}
CodePudding user response:
The bug was because you didn't specify id
for the draggable element:
<div
className="drag"
onm ouseDown={(e) => onm ousedown(e)}
onm ouseUp={(e) => onm ouseup(e)}
onm ouseMove={(e) => onm ousemove(e)}
style={{
width: "50px",
height: "50px",
background: "yellow"
}}
draggable="true"
onDragStart={(event) => dragi(event)}
>
once you add a id
to this element it will work.