import React, { useRef, useState, DragEvent } from "react"; import { CreateQuestionData } from "../types"; import { Question } from "./Question"; import { DraggableItem } from "./DraggableItem"; type Props = { questions: CreateQuestionData[]; handleQuestion: Function; deleteQuestion: Function; }; export const QuestionsList = ({ questions, handleQuestion, deleteQuestion, }: Props) => { const [items, setItems] = useState(questions); const currentItem = useRef(); const [currentItemId, setCurrentItemId] = useState(""); function arrayMove(questionArr: any[], oldIndex: number, newIndex: number) { questionArr.splice(newIndex, 0, questionArr.splice(oldIndex, 1)[0]); return questionArr; // for testing } const onDragStart = (e: DragEvent) => { currentItem.current = e.currentTarget; const { id } = e.currentTarget; const index = items.findIndex( (question: CreateQuestionData) => question._id === String(id) ); console.log(id, "drag start, ", "start index: ", index); setCurrentItemId(id); }; const onDrop = (e: DragEvent) => { e.preventDefault(); // const { id } = e.target; const { id } = e.currentTarget; const curId = e.currentTarget.id; const currentItemIndex = items.findIndex( (question: CreateQuestionData) => question._id === curId ); const dropIndex = items.findIndex( (question: CreateQuestionData) => question.id === String(id) ); console.log( id, "drop, ", "current question:", curId, ", drop index:", dropIndex, ", currentItem index:", currentItemIndex ); const newArray = arrayMove(questions, currentItemIndex, dropIndex); newArray.forEach((question, index) => { question.order = index; }); console.log("new array=", newArray); setItems([...newArray]); }; return ( <> {questions.map((question) => ( ))} ); };