The SortableList component is a powerful utility that enables drag-and-drop sorting functionality within your React application. Built on top of @dnd-kit/core, it allows for intuitive list reordering with touch and mouse support. Here’s how you can incorporate it into your project.

Basic Usage

To get started, you’ll need to supply the SortableList component with your data and a function to render each item. Here’s an example:
import SortableList from "./path-to-sortable-list-component";

const MySortableList = () => {
  // Your data
  const data = [
    { id: "item-1", content: "Item 1" },
    { id: "item-2", content: "Item 2" },
  ];

  // Function to render each item
  const itemBuilder = (dataItem, index) => <div>{dataItem.content}</div>;

  return <SortableList data={data} itemBuilder={itemBuilder} />;
};

Handling Sorting Events

SortableList allows you to handle events when sorting starts and ends. You can use these to manage state or perform actions based on the new order:
<SortableList
  data={data}
  itemBuilder={itemBuilder}
  onSortStart={() => console.log("Sorting started")}
  onSortEnd={(oldIndex, newIndex) =>
    console.log(`Moved from ${oldIndex} to ${newIndex}`)
  }
/>

Customizing Sensor Behavior

SortableList uses sensors to handle drag events. You can customize their behavior, such as the delay and tolerance for touch sensors or the distance for mouse sensors, to tailor the user experience to your application’s needs. In the component code, these are set through the useSensor hook. Adjust these settings as needed to achieve the desired responsiveness.

Implementing SortableItem

Each item in your sortable list needs to be wrapped in a SortableItem component. This component is responsible for making each item draggable. Ensure that the id prop matches the unique identifier in your data:
const itemBuilder = (dataItem, index) => (
  <SortableItem key={dataItem.id} id={dataItem.id}>
    <div>{dataItem.content}</div>
  </SortableItem>
);
With these guidelines, you’re all set to implement a dynamic and interactive sortable list in your React application. Happy sorting!