본문 바로가기

개발에 도움이 되는/React

react-beautiful-dnd

 

- react-beautiful-dnd?

 atlassian에서 만든 Drag and Drop Library이다.

https://github.com/atlassian/react-beautiful-dnd

 

 react-dnd 처럼 customizing 할 수는 없지만, 위 그림과 같이 간단하게 drag and drop을 구현하기 위해서는 사용하기 좋다.

 

 

 

- 예제

 

 - react-beautiful-dnd install 후 import 

import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

 - drag and drop 을 할 요소 상태 생성

const [fields, setfields] = useState(formList)

 - 위 그림과 같이 component를 wrapping하면 된다.

        <DragDropContext onDragEnd={handleOnDragEnd}> // Drag and Drop 기능을 위한 DragDropContext 사용
          <Droppable droppableId="fields"> // Drop 가능한 영역, droppableID랑 영역 className을 일치 시킨다.
            {(provided) => (
              // Droppable props와 ref 설정
              <div
                className="fields"
                {...provided.droppableProps}
                ref={provided.innerRef}
              >
                {fields.map((form, index) => {
                  // draggableId는 string 형으로 넣어준다.
                  let strFormId = String(form.id);
                  return (
                   // Drag 가능하게 할 component를 Wrapping
                    <Draggable
                      key={form.id}
                      draggableId={strFormId}
                      index={index}
                    >
                      {(provided) => (
                      // Drag를 위한 Draggable props와 ref 설정
                        <div
                          {...provided.draggableProps} // drag 시 움직일 요소 설정
                          {...provided.dragHandleProps} // drag handle 할 요소 설정
                          ref={provided.innerRef}
                        >
                          <FieldObject
                            key={form.id}
                            form={form}
                            handleDeleteForm={onDeleteForm}
                            onChange={handleChangeForm}
                          />
                        </div>
                      )}
                    </Draggable>
                  );
                })}
                // 이전에 drag한 아이템이 차지하는 공간을 채우기 위해 사용 (반드시 넣어준다! 없으면 에러 발생)
                {provided.placeholder} 
              </div>
            )}
          </Droppable>
        </DragDropContext>

  만약 특정 tag만 눌러서 drag and drop을 하고 싶다면 provided.dragHandleProps를 원하는 tag에 설정해주면 된다.

 

 

  - drag and drop 후 데이터 변경

  const handleOnDragEnd = (result)=>{
    const items = [...fields];
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);
    setfields(items);

  };

  위의 함수를 DragDropContext onDragEnd Event에 등록해준다.

  그러면 setfields 후 re-rendering이 되어 순서가 바뀐다.

 

 

 

실제 프로젝트 기반으로 예제를 작성한 것이라 FieldObject를 그냥 Tag라고 생각하고 보면 이해가 더 쉬울 것  같다.

 

더 자세한 예제는 아래를 참고

https://www.freecodecamp.org/news/how-to-add-drag-and-drop-in-react-with-react-beautiful-dnd/

 

반응형

'개발에 도움이 되는 > React' 카테고리의 다른 글

생명 주기(Life Cycle)  (0) 2022.03.01
Flux 패턴  (0) 2021.12.23
useEffect  (0) 2021.11.10
useState  (0) 2021.11.06
React  (0) 2021.11.05