frontPanel/src/pages/Questions/DraggableList/index.tsx

47 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-08-03 07:45:06 +00:00
import { useEffect, useState } from "react";
import { Box } from "@mui/material";
import { DragDropContext } from "react-beautiful-dnd";
import { StrictModeDroppable } from "./StrictModeDroppable";
import { DraggableListItem } from "./DraggableListItem";
import { reorder } from "./helper";
import type { ReactNode } from "react";
import type { DropResult } from "react-beautiful-dnd";
type DraggableListProps = {
items: ReactNode[];
};
export const DraggableList = ({ items }: DraggableListProps) => {
const [listItems, setListItems] = useState(items);
useEffect(() => {
setListItems(items);
}, [items]);
const onDragEnd = ({ destination, source }: DropResult) => {
if (destination) {
const newItems = reorder(listItems, source.index, destination.index);
setListItems(newItems);
}
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<StrictModeDroppable droppableId="droppable-list">
{(provided) => (
<Box ref={provided.innerRef} {...provided.droppableProps}>
{listItems.map((item, index) => (
<DraggableListItem key={index} item={item} index={index} />
))}
{provided.placeholder}
</Box>
)}
</StrictModeDroppable>
</DragDropContext>
);
};