본문 바로가기
카테고리 없음

React Table 06 : 간단한 정렬 구현하기 Sorting Table

by 이승보 2021. 8. 24.
728x90

각 열의 헤더를 누르면 오름차순, 내림차순으로 정렬되는 기능을 구현해본다.
키보드의 'shift'를 누른 채로 헤더를 클릭하면 중복 정렬이 가능하다.
정렬이 되면 열의 이름에 화살표 표시로 오름/내림차순 정렬 중이라는 것을 표시해준다.

import { useTable, useSortBy } from "react-table";


export const SortingTable = () => {
  const columns = useMemo(() => COLUMNS, []);
  const data = useMemo(() => MOCK_DATA, []);

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow,
  } = useTable({ columns, data }, useSortBy);
  
	  <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                {column.render("Header")}
                <span>
                  {column.isSorted ? (column.isSortedDesc ? " ⬇︎" : " ⬆︎") : ""}
                </span>
              </th>
            ))}
          </tr>
        ))}
        </thead>

 

1. react-table 에서 <useSortBy> 훅을 import 해준다.

2. useTable 의 인자로 useSortBy를 추가해준다.

3. header에서 th 태그의 getHeaderProps() 의 인자로 <column.getSortByToggleProps()>를 추가해준다.

4. 3번까지 완료하면 정렬 기능 구현은 끝났지만, 정렬 중이라는 것을 알 수 있게 하기 위해서 <span> 태그 안에 isSorted를 사용해서 아이콘 표시를 해준다.
- isSorted(Boolean) : 이 열이 현재 정렬되고 있는지 여부
- isSortedDesc(Boolean) : 열이 현재 정렬되어 있는 경우 정렬 방향이 내림차순인지 여부. True = 내림차순, False = 오름차순, Undefined = 현재 열 정렬안되어 있음

 

결과화면

 

 

https://www.youtube.com/watch?v=zypbcG3ZVnc&list=PLC3y8-rFHvwgWTSrDiwmUsl4ZvipOw9Cz&index=6&ab_channel=Codevolution 

https://react-table.tanstack.com/docs/api/useSortBy

 

API Reference: useSortBy

Subscribe to our newsletter The latest TanStack news, articles, and resources, sent to your inbox.

react-table.tanstack.com

 

728x90
반응형

댓글