Search code examples
javascriptreactjsreact-beautiful-dnd

Unable to drag and drop Components in same Droppable react-beautiful-dnd


What's happening is when I have multiple items in a column and attempt to drag one, only one is shown and according to the lessons found here I should be at the point where I can move items within the same column but can not. In React dev tools state and r-b-dnd ids look good, but what do I know? I'm just a rookie. Here is what I have in my onDragEnd so far.

  onDragEnd = result => {
    const { destination, source, draggableId } = result;
    if (!destination) return;
    if (
      destination.droppableId === source.droppableId &&
      destination.index === source.index
    ) {
      return;
    }
    let start = this.state.list[source.droppableId];
    let finish = this.state.list[destination.droppableId];
    if (start === finish) {
      let updatedList = this.state.list.map(obj => {
        if (obj.id === source.droppableId) {
          obj.cards.splice(source.index, 1);
          obj.cards.splice(destination.index, 0, draggableId);
        }
        return obj;
      });
      this.setState({ list: updatedList });
    }

And my app can be found here. Thanks.


Solution

  • In your code, in onDragEnd you have this code which is why you can't rearrange items on same list. When you move items across same list, source and destination Droppable IDs will be same.

    if (destination.droppableId === source.droppableId && destination.index === source.index) {
      console.log("they're equal");
      return;
    }
    
    1. On your component, the dragabble ID is same for all items in the list. It should be unique for every draggable item.
    const Card = props => {
      return (
        // This is NOT unique. This should be dynamic, we should use idx probably.
        <Draggable draggableId={props.col + "-" + props.color} index={props.idx}>
          {provided => (
    

    After correcting these two, Im able to move items: https://codesandbox.io/s/r5z28w85yo. Hope this is helpful.