Save Position of dragged items with Dragula Drag and Drop, React Version (react-dragula)

4.8k Views Asked by At

I am using react-dragula (react-dragula) to drag and drop elements. How should I save the items positions after drop.

  dragDecorator = () => {
            let options = { };
            Dragula([componentBackingInstance], options);
          }; 

     <div className="wrapper" ref={this.dragDecorator}>
       <div className="container col-md-4" id="0">
         <div className="panel panel-white" id="A1">
         </div>
         <div className="panel panel-white" id="A2">
        </div>
       </div>
       <div className="container col-md-4" id="0">
         <div className="panel panel-white" id="B1">
         </div>
         <div className="panel panel-white" id="B2">
        </div>
       </div>
    </div>
1

There are 1 best solutions below

1
On BEST ANSWER
  dragDecorator = (componentBackingInstance) => {
    if (componentBackingInstance) {
      let options = {};

      const dragula = Dragula([componentBackingInstance], options);
      dragula.on('drop', (el, target, source, sibling) => {
        const newColumnIndex = parseInt(get(target, 'id'));
        const previousColumnIndex = parseInt(get(source, 'id'));
        const belowId = get(sibling, 'id');
        const itemId = get(el, 'id');

        let columns = this.state.columns;
        if (belowId === undefined) {
          const newItemIndex = columns[newColumnIndex].items.length;
          columns[previousColumnIndex].items.splice(columns[previousColumnIndex].items.indexOf(itemId), 1);
          columns[newColumnIndex].items.splice(newItemIndex, 0, itemId);
          this.setState({columns});
        }
        else {
          const newItemIndex = columns[newColumnIndex].items.indexOf(belowId);
          columns[previousColumnIndex].items.splice(columns[previousColumnIndex].items.indexOf(itemId), 1);
          columns[newColumnIndex].items.splice(newItemIndex, 0, itemId);
          this.setState({columns});
        }

        if (this.props.onDrag !== undefined) {
          this.props.onDrag(columns);
        }
      })
    }
  };

Columns will return an array including the new positions of dragged items in each column based on their IDs.