개발 노트

정렬버튼 추가하기 본문

React

정렬버튼 추가하기

한츄 2024. 2. 26. 18:03

1. 버튼 컴포넌트 제작

import { useButtonStore } from "@/store/useButtonStore";


const SortButton: React.FC = () => {
const {activeSortButton, setActiveSortButton} = useButtonStore()
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>): void => {
    const sort = e.currentTarget.dataset.sort;

    if (!sort) return
      switch (sort) {
        case 'update':
          setActiveSortButton(sort);
          break;

        case 'farmName':
          setActiveSortButton(sort);
          break;

        case 'farmCode':
          setActiveSortButton(sort);
          break;
      }
  };
  // console.log(activeButton);
  
  return (
    <div className="fixed lg:top-6 lg:left-96 md:left-44 md:top-10 sm:left-40 top-[38px] left-12 text-[10px] z-50 md:text-sm border rounded-xl overflow-hidden">
      <button
        type="button"
        className={`pl-3 pr-1.5 hover:bg-[#A7DD9E] acvtive:bg-[#A7DD9E] ${activeSortButton === 'update' ? 'bg-state-green text-white ' : ''}`}
        data-sort="update"
        onClick={handleClick}
      >
        업데이트 순
      </button>
      <button
        type="button"
        className={`px-1.5 border-x hover:bg-[#A7DD9E] acvtive:bg-[#A7DD9E] ${activeSortButton === 'farmName' ? 'bg-state-green text-white' : ''}`}
        data-sort="farmName"
        onClick={handleClick}
      >
        농장이름 순
      </button>
      <button
        type="button"
        className={`pl-1.5 pr-3 hover:bg-[#A7DD9E] acvtive:bg-[#A7DD9E] ${activeSortButton === 'farmCode' ? 'bg-state-green text-white' : ''}`}
        data-sort="farmCode"
        onClick={handleClick}
      >
        농장코드 순
      </button>
    </div>
  );
};

export default SortButton;

 

 

2. 버튼의 값을 저장할 zustand store만들기

import {create} from 'zustand';

type Store = {
  activeSortButton: string | null;
  setActiveSortButton: (name: string) => void;
};

export const useButtonStore = create<Store>((set) => ({
  activeSortButton: null,
  setActiveSortButton: (name) => set(() => ({ activeSortButton: name })),
}));

 

 

3. return부분에서 필요한부분에 버튼컴포넌트 호출

        <SortButton />

 

 

4. useButtonStore에 저장해뒀던 activeSortButton의 값을 이용해 정렬하기

  const farmCodes = Object.keys(groupedMessages);
  // activeSortButton의 값에 따라 farmCodes를 정렬
  let sortedFarmCodes;
  if (activeSortButton === 'update') {
    sortedFarmCodes = farmCodes.sort((a, b) => {
      const lastMessageTimeA = extractTime(groupedMessages[a].messages[groupedMessages[a].messages.length - 1].message);
      const lastMessageTimeB = extractTime(groupedMessages[b].messages[groupedMessages[b].messages.length - 1].message);
      return new Date(lastMessageTimeB).getTime() - new Date(lastMessageTimeA).getTime(); // 내림차순 정렬
    });
  } else if (activeSortButton === 'farmName') {
    sortedFarmCodes = [...farmCodes].sort(); // 이름 순으로 정렬
  } else if (activeSortButton === 'farmCode') {
    sortedFarmCodes = [...farmCodes].sort((a, b) => a.localeCompare(b));
  } else {
    sortedFarmCodes = [...farmCodes]; // 기본값은 원본 farmCodes를 그대로 사용
  }