atlassian / react-beautiful-dnd

Beautiful and accessible drag and drop for lists with React
https://react-beautiful-dnd.netlify.app
Other
33.23k stars 2.53k forks source link

What part of this code makes the other elements update their sort number? #1526

Closed revialim closed 4 years ago

revialim commented 4 years ago

Hi, I'm trying out the drag-and-drop for the first time and edited the functional example that was given in the docs to work as I'd like to use it. Now my problem occurs when I applied it to my own code I get some errors when I drag elements to the very beginning or very end of the list. When calling reorder quite logically there is no element in my list at endIndex when dragging to the last position. In the codesandbox example, though, it seems to work anyways and all elements above have the sort number updated as well. I would like to know what happens in the code, that I'm missing, to make it work on my local project as well. Edit Using react-beautiful-dnd with hooks

Expected behavior

Dragging element locally behaves the same as in the codesandbox example.

Actual behavior

Dragging element in local project causes undefined error since referencing list outside of scope.

My local workaround (below) works fine, so this is rather a question, why it doesn't cause a bug in the codesandbox example.

const reorder = (list, startIndex, endIndex) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  const endIndexPrev = endIndex === 0? 0 : result[endIndex-1].sort;
  const endIndexNext = endIndex === list.length-1? list.length+1: result[endIndex].sort;
  removed.sort = (endIndexNext+endIndexPrev)/2;
  result.splice(endIndex, 0, removed);

  return result;
};
revialim commented 4 years ago

After some more investigation I found out, that the item in the codesandbox sample doesn't get moved when trying to move it to first or last position, but jumps back to its previous position without index out of bounds error. In some cases visually it appears like the ids get reassigned.