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

React Table 07 : 포멧을 이용한 정렬

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

지난 시간에 정렬을 구현했는데, 문제가 있다! 
위 이미지의 Date of Birth 필드를 보면 실제 날짜포멧으로 정렬된 것이 아니라 String 타입으로 인식해서 맨 앞의 숫자들을 기준으로 정렬을 하고 있는 것을 알 수 있다. date 필드 외에도 특정 필드들은 단순히 숫자나 글자 기준이 아닌 다른 형식으로 정렬을 해줘야 할 때가 있다.

이번 시간에는 date functions package 설치를 통해서 date 필드에 포멧을 설정해줘보자.

주의사항 :
Data.json 파일의 date 들은 RFC2822 또는 ISO 8601 날짜를 나타내는 문자열로 되어 있어야 한다.
Javascript의 new Date(), date.parse() 참고하기
(나는 Mock.json 새로 만들기 귀찮아서...split으로 일일이 나눠줬음...)

 

1. date function package설치

yarn add date-fns

2. columns.js 파일에 format import 해주기

import {format} from 'date-fns'

3. 'Date of Birth' 열에 Cell 속성 추가
- Cell 속성은 UI에서 렌더링 되는 내용을 컨트롤한다. 해당 열의 각 행마다 지정해주는 function 이라 생각해주면 된다.

{
    Header: "Date of Birth",
    Footer: "Date of Birth",
    accessor: "date_of_birth",
	Cell: ({ value }) => {
      return format(new Date(value), "dd/MM/yyyy");
	},
 },
 
 
 //ISO 타입데이터로 안되어 있을 경우에
 Cell: ({ value }) => {
      const dateArr = value.split("/");
      return format(
        new Date(dateArr[2], dateArr[0], dateArr[1]),
        "MMM/dd/yyyy"
      );
    },

    sortType: (A, B, id, desc) => {
      const arrA = A.original[id].split("/");
      const arrB = B.original[id].split("/");
      const dateA = new Date(arrA[2], arrA[0], arrA[1]);
      const dateB = new Date(arrB[2], arrB[0], arrB[1]);

      if (dateA > dateB) return -1;
      if (dateB > dateA) return 1;
      return 0;
    },

 

결과화면

 

 

참고사이트

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

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

 

Date.parse() - JavaScript | MDN

Date.parse () 메서드는 날짜의 문자열 표현을 구문 분석하고 1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 반환하거나 문자열이 인식되지 않거나 경우에 따라 잘못된 날짜 값을 포함하는 경우 NaN

developer.mozilla.org

https://date-fns.org/v2.23.0/docs/format

 

Modern JavaScript Date Utility Library

date-fns provides the most comprehensive yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js.

date-fns.org

 

custom Sort Type 관련

https://stackoverflow.com/questions/63927644/how-does-one-supply-a-custom-sort-function-for-react-table-7

 

How does one supply a custom sort function for react table 7?

The documention for useSortBy sortType properties says: sortType: String | Function(rowA: , rowB: , columnId: String, desc: Bool) Used to compare 2 rows of data and order...

stackoverflow.com

https://react-table-omega.vercel.app/docs/api/useSortBy#column-options

 

API Reference: useSortBy

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

react-table.tanstack.com

728x90
반응형

댓글