admin管理员组

文章数量:1122846

i am using dndkit in a cra project jsx and have an arr ex.

const items = [
  { id: "1", name: "Item A", checked: true },
  { id: "2", name: "Item B", checked: false },
  { id: "3", name: "Item C", checked: true },
  { id: "4", name: "Item D", checked: false },
];

then i want to drag items which are checked=true only but not others so i sorted them now i want the dragged item to drag over only items which are checked=true not to be over items checked=false as they are not even exist and the item ended at the last ele of arr checked=true so the list will show all the items sorted checked first and those items can be moved or dragged over each overs but they cannot be over the not checked items can you help me !!

import { DndContext, closestCenter } from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
} from "@dnd-kit/sortable";
import SortableItem from "./SortableItem"; // عنصر قابل للسحب (تعريف مخصص)

const items = [
  { id: "1", name: "Item A", checked: true },
  { id: "2", name: "Item B", checked: false },
  { id: "3", name: "Item C", checked: true },
  { id: "4", name: "Item D", checked: false },
];

function App() {
  const [sortedItems, setSortedItems] = React.useState(
    items.sort((a, b) => (a.checked === b.checked ? a.name.localeCompare(b.name) : b.checked ? -1 : 1))
  );

  const handleDragEnd = (event) => {
    const { active, over } = event;

    if (!over || active.id === over.id) return;

    const activeIndex = sortedItems.findIndex((item) => item.id === active.id);
    const overIndex = sortedItems.findIndex((item) => item.id === over.id);

    // Move item in the array
    const newArray = arrayMove(sortedItems, activeIndex, overIndex);

    // Re-sort `checked=true` to stay together
    const checkedItems = newArray.filter((item) => item.checked);
    const uncheckedItems = newArray.filter((item) => !item.checked);

    setSortedItems([...checkedItems, ...uncheckedItems.sort((a, b) => a.name.localeCompare(b.name))]);
  };

  return (
    <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={sortedItems.map((item) => item.id)}>
        {sortedItems.map((item) => (
          <SortableItem key={item.id} id={item.id} disabled={!item.checked}>
            {item.name}
          </SortableItem>
        ))}
      </SortableContext>
    </DndContext>
  );
}

export default App;

本文标签: sortingrestriction to items according to condition in dndkitStack Overflow