Mark Vital
Mark Vital

Reputation: 950

How to drag multiple objects at once in React?

I would like to drag multiple objects at once (preserving their positions in DOM). So if the objects overlap, the overlapping order should stay the same.

enter image description here

I was trying to achieve this using react-draggable or react-dnd - the most popular drag and drop frameworks on top of Google.

In react-dnd, the proposed solution would be to keep track of selected items and implement custom drag-layer. However this way the position in DOM will be lost, so visually objects would be overlapping each other differently.

I haven't found how to do it in react-draggable. Maybe there is a way to have some sort of draggableGroup attribute to indicate a group of draggable objects? Has anyone implemented anything like this before?

Here are my experiments with react-draggable: codepen.io/markvital/pen/gOaRMNX.

Multiple objects can be selected, but only one is draggable.

const canvasSize = {width:"600", height:"400"}

function DraggableItem({id, selected, onSelect, children}) {
    const [isDragging, setIsDragging] = React.useState(false);
    const isSelected = selected && selected.indexOf(id) >= 0;

    function handleClick (e, idx) {
        if (e.shiftKey) {
            onSelect(idx);
        }
    }

    return (
        <ReactDraggable
            onStart={ () => setIsDragging(true) }
            onStop={ () => { setIsDragging(false); } }
            disabled={!isSelected}
        >
            <g>
                <g className={`item ${isSelected ? "selected" : ""} ${isDragging ? "dragging" : ""}`} onClick={e => handleClick(e, id)}>
                    {children}
                </g>
            </g>
        </ReactDraggable>
    )
}

function DraggableElements(props) {
    const {children, ...restProps } = props;
    const draggable = children.map((child, idx) => <DraggableItem key={idx} id={idx} {...restProps}>{child}</DraggableItem>);
    return(
        <>{draggable}</>
    )
}

function Canvas(props) {
    const [selected, setSelected] = React.useState([]);
    function select(idx){
        const newSelection = selected.indexOf(idx) >= 0 ? selected.filter(item => item != idx) : [...selected, idx];
        setSelected( newSelection );
    }

    return (
            <svg className="canvas" {...canvasSize} xmlns="http://www.w3.org/2000/svg"  >
                <DraggableElements selected={selected} onSelect={select}>
                    <rect x="120" y="250" width="100" height="100" fill="lightgrey" />
                    <circle cx="400" cy="100" r="75"  fill="lightblue" />
                    <polygon points="160,300 200,100 350,230" fill="grey" />
                    <rect x="50" y="50" width="200" height="100" fill="lightgreen" />
                    <rect x="465" y="70" width="100" height="150" rx="25" fill="pink" />
                    <ellipse cx="400" cy="260" rx="130" ry="75" fill="lightyellow" />
                </DraggableElements>
            </svg>
    );
}

function App() {
  return (
    <div className="App">
        <Canvas />
        <div> Hold SHIFT key to select multiple figures, than drag </div>
    </div>
  );
}



let mountNode = document.getElementById("app");
ReactDOM.render(<App />, mountNode);

Upvotes: 0

Views: 4817

Answers (1)

Mark Vital
Mark Vital

Reputation: 950

One of the solutions using react-draggable would be to store some state delta in the parent component, that describes cursor position offset while dragging:

function Canvas(props) {
  const [delta, setDelta] = useState(null); // cursor offset while dragging, {x:0, y:0}
  const [selected, setSelected] = useState([]);

  return (
      // draggable elements, each wrapped in react-draggable
      <DraggableElements delta={delta} onDrag={handleDrag}>
        //..
      </DraggableElements>
  )
}

and then pass that delta to children, that are wrapped in Draggable component

<ReactDraggable onDrag={ (e, data) => { onDrag({x: data.x, y: data.y }, id) } }>
   <g style={delta ? {transform: `translate(${delta.x}px, ${delta.y}px)`} }>
      //...
   </g> 
</ReactDraggable>

Here is the working version, based on my previous example: codepen.io/markvital/pen/vYNZXgW

Would love to see more optimal solution.

Upvotes: 1

Related Questions