지난 시간에 정렬을 구현했는데, 문제가 있다!
위 이미지의 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://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
https://date-fns.org/v2.23.0/docs/format
custom Sort Type 관련
https://react-table-omega.vercel.app/docs/api/useSortBy#column-options
댓글