티스토리 뷰

반응형

[react/javascript] 리액트 table에서 drag로 순서변경하기

 

#라이브러리

https://github.com/clauderic/react-sortable-hoc

 

GitHub - clauderic/react-sortable-hoc: A set of higher-order components to turn any list into an animated, accessible and touch-

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️ - GitHub - clauderic/react-sortable-hoc: A set of higher-order components to turn a...

github.com

 

#설치

$ npm install react-sortable-hoc --save

 

#샘플코드

import React, { useEffect, useState } from "react";
import { sortableContainer, sortableElement } from "react-sortable-hoc";
import { arrayMoveImmutable } from "array-move";

const SortableItem = sortableElement(({ value }) => (
  <tr>
    <td>{value}</td>
    <td>{value}</td>
  </tr>
));
const SortableContainer = sortableContainer(({ children }) => {
  return (
    <table>
      <thread>
        <th>aaaa</th>
        <th>bbbb</th>
      </thread>
      {children}
    </table>
  );
});
const History = () => {
  useEffect(() => {
    setList(["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"]);
  }, []);
  const [list, setList] = useState([]);
  const onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(({ items }) => ({
      items: arrayMoveImmutable(items, oldIndex, newIndex),
    }));
  };
  return (
    <SortableContainer onSortEnd={onSortEnd}>
      {list.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </SortableContainer>
  );
};
export default History;

 

최적화되어 아주 잘되고, 모듈화도 매우 쉽다

#react #sortable #drag #리액트 #드래그 #정렬 #테이블 #table

반응형
댓글
반응형