In React, you can implement drag and drop functionality using the drag
and drop
events and the DataTransfer
interface.
Here’s an example of how you can implement drag and drop in React:
import React, { useRef } from 'react';
const DragDrop = () => {
const dragRef = useRef(null);
const handleDragStart = e => {
const target = e.target;
e.dataTransfer.setData('card_id', target.id);
setTimeout(() => {
target.style.display = 'none';
}, 0);
};
const handleDragOver = e => {
e.stopPropagation();
};
const handleDrop = e => {
e.preventDefault();
const cardId = e.dataTransfer.getData('card_id');
const card = document.getElementById(cardId);
dragRef.current.appendChild(card);
card.style.display = 'block';
};
return (
<div
ref={dragRef}
onDrop={handleDrop}
onDragOver={handleDragOver}
style={{ width: '300px', height: '300px', border: '1px solid black' }}
>
<div
id="card1"
draggable
onDragStart={handleDragStart}
style={{ width: '100px', height: '100px', border: '1px solid red' }}
>
Drag me!
</div>
</div>
);
};
export default DragDrop;
In this example, we have a div element with the dragRef
ref that represents the drop zone. We also have a div element with the handleDragStart
event handler that represents the draggable element.
When the user starts dragging the draggable element, the handleDragStart
event handler is called, and we set the data that we want to transfer using the setData()
method of the DataTransfer
interface. We also hide the draggable element by setting its display
style to none
.
When the user drags the draggable element over the drop zone, the handleDragOver
event handler is called, and we prevent the default behavior of the dragover
event using the stopPropagation()
method.
When the user drops the draggable element on the drop zone, the handleDrop
event handler is called, and we retrieve the data that was transferred using the getData()
method of the DataTransfer
interface. We then append the draggable element to the drop zone and show it by setting its display
style to block
.
Comment on “React JS- How to Drag and Drop”