FrontEnd/React
react-beautiful-dnd
hanseom
2023. 11. 22. 21:00
반응형
react-beautiful-dnd 모듈을 사용하여 TodoApp에 Drap and Drop 기능을 추가합니다.
react-beautiful-dnd
npm install react-beautiful-dnd --save


index.js(StrictMode 제거)
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
// <React.StrictMode>
<App />
// </React.StrictMode>
);
Lists.js
import React from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";
export default function Lists({ todoData, setTodoData }) {
... 생략 ...
const handleEnd = (result) => {
// 목적지가 없으면(이벤트 취소) 이 함수를 종료합니다.
if (!result.destination) return;
// 리액트 불변성을 지켜주기 위해 새로운 todoData를 생성합니다.
const newTodoData = todoData;
// 1. 변경시키는 아이템을 배열에서 지워줍니다.
// 2. return 값으로 지워진 아이템을 잡아줍니다.
const [reorderedItem] = newTodoData.splice(result.source.index, 1);
// 3. 원하는 자리에 reorderedItem을 insert 해줍니다.
newTodoData.splice(result.destination.index, 0, reorderedItem);
setTodoData(newTodoData);
};
return (
<div>
<DragDropContext onDragEnd={handleEnd}>
<Droppable droppableId="todo">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{todoData.map((data, index) => (
<Draggable
key={data.id}
draggableId={data.id.toString()}
index={index}
>
{(provided, snapshot) => (
<div
key={data.id}
{...provided.draggableProps}
ref={provided.innerRef}
{...provided.dragHandleProps}
className={`${
snapshot.isDragging ? "bg-gray-400" : "bg-gray-100"
} flex items-center justify-between w-full px-4 py-1 my-2 text-gray-600 border rounded`}
>
<div className="items-center">
<input
type="checkbox"
onChange={() => handleCompleChange(data.id)}
defaultChecked={false}
/>{" "}
<span
className={
data.completed ? "line-through" : undefined
}
>
{data.title}
</span>
</div>
<div className="items-center">
<button onClick={() => handleClick(data.id)}>x</button>
</div>
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
</div>
);
}
불변성
불변성이란 값이나 상태를 변경할 수 없는 것을 의미합니다. 자바스크립트의 원시 타입은 불변성을 가지지만, 참조 타입은 그렇지 않습니다(mutable).
- 원시 타입: Boolean, String, Number, null, undefined, Symbol (고정된 크기로 Call Stack 메모리에 저장, 실제 데이터가 변수에 할당됩니다.)
- 참조 타입: Object, Array (데이터 크기가 정해지지 않고 Call Stack 메모리에 저장, 데이터의 값이 heap에 저장되며 변수에 heap 메모리의 주소값이 할당됩니다.)
불변성을 지켜야 하는 이유
- 원본 데이터가 변경되면 이를 참조하고 있는 다른 객체에서 예상치 못한 오류가 발생할 수 있습니다.
- 프로그래밍의 복잡도가 올라갑니다.
- React에서 변경된 사항을 확인 후 업데이트하기 때문에 불변성을 지켜줘야 합니다.
불변성을 지키키 위해서는 참조 타입에서 새로운 배열을 반환하는 메소드를 사용하면 됩니다.
- spread operator, map, filter, slice, reduce
- 원본 데이터를 변경하는 메소드: splice, push
const array = [1,2,3,4];
const sameArray = array;
sameArray.push(5); // 원본 데이터 변경
console.log(array === sameArray); // true
// 불변성을 지키는 코드
const array = [1,2,3,4];
const difArray = [...array, 5];
console.log(array === difArray); // false
[참고 정보]
반응형