React Drag and Drop Implementation Guide

In React, drag-and-drop free layout can be implemented using the HTML5 drag-and-drop API. Here is a simple implementation example:

First, create a Draggable component to wrap the draggable elements.

import React from 'react';

const Draggable = ({ id, onDragStart, children }) => {
  const handleDragStart = (event) => {
    event.dataTransfer.setData('text/plain', id);
    onDragStart(id);
  };

  return (
    <div
      draggable
      onDragStart={handleDragStart}
      style={{ cursor: 'move' }}
    >
      {children}
    </div>
  );
};

export default Draggable;

Next, create a container element in the parent component and listen for drag and drop events.

import React, { useState } from 'react';
import Draggable from './Draggable';

const FreeLayout = () => {
  const [draggedItem, setDraggedItem] = useState(null);
  const [items, setItems] = useState([]);

  const handleDrop = (event) => {
    event.preventDefault();
    const itemId = event.dataTransfer.getData('text/plain');
    const newItem = { id: itemId, x: event.clientX, y: event.clientY };
    setItems([...items, newItem]);
    setDraggedItem(null);
  };

  const handleDragOver = (event) => {
    event.preventDefault();
  };

  const handleDragStart = (itemId) => {
    setDraggedItem(itemId);
  };

  return (
    <div
      onDrop={handleDrop}
      onDragOver={handleDragOver}
      style={{ width: '500px', height: '500px', border: '1px solid black' }}
    >
      {items.map((item) => (
        <div
          key={item.id}
          style={{
            position: 'absolute',
            left: item.x,
            top: item.y,
            border: '1px solid red',
            padding: '10px',
          }}
        >
          {item.id}
        </div>
      ))}
      <Draggable id="item1" onDragStart={handleDragStart}>
        Item 1
      </Draggable>
      <Draggable id="item2" onDragStart={handleDragStart}>
        Item 2
      </Draggable>
    </div>
  );
};

export default FreeLayout;

In the example above, the state in the FreeLayout component is used to store the position information of the dragged elements. The Draggable component is used to encapsulate draggable elements and trigger a callback function when dragging starts.

Listen for the drop and dragover events on the container element, and in the drop event, retrieve the dragged element information and add it to the state. When triggering the dragstart event on the dragged element, store the element’s id in the state.

Finally, render the dragged element based on the position information in the state, and set its position to absolute.

This achieves a simple free drag layout, which can be further extended and optimized as needed.

bannerAds