import React from 'react'
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
export default function Lists({ todoList, setTodoList }) {
const handleDelete = (id) => {
let newTodoList = todoList.filter(item => {
return item.id !== id;
})
setTodoList(newTodoList);
}
const handleComplete = (id) => {
let newTodoList = todoList.filter(item => {
if (item.id === id) {
item.completed = !item.completed;
}
return item;
})
setTodoList(newTodoList);
}
const handleEnd = (result) => {
console.log(result)
// 변경된게 없으면 함수 종료
if (!result.destination) return;
// 불변성을 지켜주기 위해서 데이터를 카피해서 가져옴
const newTodoList = todoList;
// 재배열될 아이템을 잘라서 가져옴
const [reorderdItem] = newTodoList.splice(result.source.index, 1);
// 재배열된 아이템을 도착지 인덱스에 추가함 -> 위치 변경 완료
newTodoList.splice(result.destination.index, 0, reorderdItem);
setTodoList(newTodoList);
}
return (
<div>
<DragDropContext onDragEnd={handleEnd}>
<Droppable droppableId='Unique-droppable-id' >
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{todoList.map((data, index) => (
<Draggable
key={data.id}
draggableId={data.id.toString()}
index={index}
>
{(provided, snapshot) => (
<div key={data.id}
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
className={`${snapshot.isDragging ? "bg-gray-400" : "bg-gray-100"} 'flex item-center justify-between w-full px-4 py-1 my-2 text-gray-600 bg-gray-100 border rounded`}>
<div className='item-center'>
<input type="checkbox"
defaultChecked={false}
onChange={() => handleComplete(data.id)} />
<span
className={data.completed ? "line-through" : undefined}>{data.title}</span>
<button
className='px-4 py-2 float-right'
onClick={() => handleDelete(data.id)}>X</button>
</div>
</div>
)}
### </Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
</div>
)
}
DragDropContext, Droppable, Draggable 컴포넌트들을 계층적으로 넣어주어야 한다.
Draggable 컴포넌트는 드래그를 할 수 있는 컴포넌트이고 Droppable 컴포넌트는 해당 섹터 안에서 Draggable 컴포넌트를 내려놓을 수 있는 컴포넌트이다. 즉 Draggable 컴포넌트를 drop할 때, droppable 컴포넌트 내에다가 드랍을 해야만 컴포넌트를 이동시킬 수 있고 또 그 구역이 DragDropContext 컴포넌트 내에 있어야만 이벤트를 받아서 동작을 처리할 수 있다.
<Droppable droppableId='Unique-droppable-id' >
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
<Draggable
key={data.id}
draggableId={data.id.toString()}
index={index}
>