Sortablejs + React sorting unexpected behaviour

45 Views Asked by At

I am trying to do what the react-sortablejs library does but a simpler aproach and I am having trouble making it work. I just have a simple drag and drop list and I want to sort items while keeping track of the list on the react state.

I leave an example of my approach to this particular case:

Link to example

const simpleListItems = [
  { label: 'Details', id: 'details-0' },
  { label: 'Rerun', id: 'rerun-0' },
  { label: 'Skip', id: 'skip-0' },
  { label: 'Update', id: 'update-0' },
];

const App = () => {
  const listRef = useRef();
  const [list, setList] = useState(simpleListItems);
  
  useEffect(() => {
    if (listRef.current) {
      const options = {
        group: 'share',
        animation: 100,
        onUpdate: ({ newIndex, oldIndex, to }) => {
          const updatedItems = Array.from(to.children).map((t) => ({id: t.id, label: t.innerText }))
          
          console.log('updatesItems', updatedItems)
          setTimeout(() => {
            setList(updatedItems);
          }, 1000)
        },
      };

      Sortable.create(listRef.current, options);
    }
  }, [listRef]);
  
  return(
    <div ref={listRef}>
      {list?.map(item => (
        <div id={item.id} style={{ border: '1px solid black', width: '200px', height: '50px' }}>
          {item.label}
        </div>
      ))}
    </div>
  );
}

I put there a setTimeout so it is visible that sortablejs updates the dom correctly and whenever I update the react state it goes back to the previous state and flags the element that is being dragged in this case a div to draggable=false

The console log also shows that the data from updatedItems is correct and should work.

0

There are 0 best solutions below