4

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 Answers1

2
  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.

  • Hey, what would be solution for this kind of scenario ? list state is array of objects, this.state.files = [{ name: 'a', order: 0 }, { name: 'b', order: 1 }, {name: 'c', order: 2}] and in render method i'm mapping over state array, which is dragula container. how to update state based on drop method ? – Dimi Mikadze Oct 17 '16 at 13:00