so woon!

[REACT] Drag and Drop1 본문

ReactJS/개념정리

[REACT] Drag and Drop1

xowoony 2023. 4. 25. 17:58

학습일 : 2023. 04. 25



이번에는 드래그 앤 드롭 리스트를 만들어보고자 한다.

 

 

예를 들자면,
todo를 작성해 준것이 있다면 그것을
todo, doing, done으로 옮길 수 있게 해볼 것이다.

 

 


이를 구현하기 위해서
react-beautiful-dnd를 사용할 건데,
아주 유명한 라이브러리이고 유용하고 사용하기에 쉽다고 한다.
여기에 recoil도 연습해보도록 하자.

 

 


https://www.npmjs.com/package/react-beautiful-dnd

 

react-beautiful-dnd

Beautiful and accessible drag and drop for lists with React. Latest version: 13.1.1, last published: 8 months ago. Start using react-beautiful-dnd in your project by running `npm i react-beautiful-dnd`. There are 1557 other projects in the npm registry usi

www.npmjs.com

 


터미널에 입력 후 설치

npm i react-beautiful-dnd
npm i --save-dev @types/react-beautiful-dnd



import 해준다.

import { DragDropContext } from "react-beautiful-dnd";




<App.tsx>
onDragEnd라는 함수는 유저가 드래그를 끝낸 시점에 불려지는 함수이고 
필수로 적어주어야 한다.


일단 임시로 onDragEnd를 만들어주고 적용해놓겠음


DragDropContext는 또한 자식이 필수로 필요하기 때문에
일단 div 태그를 하나 넣어주도록 하겠음


Droppable은 droppableId prop이 필요하기 때문에 작성해주어야 하고
자식이 필요하기 때문에 안에 ul 태그를 넣어주겠다.

 

그런데
Droppable의 자식은 리액트 요소이면 안되기 때문에
{} 안에 넣어주어 뱉어주겠다.


Draggable도 똑같이 작성해주고 필수 prop인 draggableId와 index를 적어주도록 한다.
index는 sorting을 위한 것이라 0, 1으로 주겠다.

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

function App() {
  const onDragEnd = () => {};
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <div>
        <Droppable droppableId="one">
          {() => (
            <ul>
              <Draggable draggableId="first" index={0}>
                {() => <li>One</li>}
              </Draggable>
              <Draggable draggableId="second" index={1}>
                {() => <li>Two</li>}
              </Draggable>
            </ul>
          )}
        </Droppable>
      </div>
    </DragDropContext>
  );
}

export default App;

 

 

 



다음 글에 계속~




 

 

'ReactJS > 개념정리' 카테고리의 다른 글

[REACT] Drag and Drop - dragHandleProps  (0) 2023.04.26
[REACT] Drag and Drop2  (0) 2023.04.25
[REACT] 클릭시 카테고리 바꾸기2  (1) 2023.04.20
[REACT] 클릭시 카테고리 바꾸기1  (0) 2023.04.19
[REACT] Refactoring  (0) 2023.04.19
Comments