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
版权声明:本文标题:sorting - restriction to items according to condition in dndkit - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736282932a1926802.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论