드롭다운 버튼과 정렬 기능
해본 적은 없는데 어려울 건 없어보인다
DropDownButton 컴포넌트 생성
코드
DropDownButton
더보기
function DropDownButton(props: DropDownButtonProps) {
// 정렬 기준 항목들을 내려받고, 정렬기준 설정 가능
const { sortByList, sortBy, setSortBy } = props;
// true면 펼쳐진 상태, false면 닫힌 상태
const [isActive, setIsActive] = useState(false);
return (
<>
<div className='relative inline-block'>
{/* active 상태에 따라 드롭다운이 펼쳐지거나 접힘
버튼을 클릭할 때마다 active 상태를 변경 */}
<button
className='text-white cursor-pointer w-32 py-2 rounded'
onClick={() => setIsActive((prev) => !prev)}
>
{/* 해당 정렬 기준을 선택하면 드롭다운 버튼에 표시 */}
{sortBy}
{/* 펼쳐지면 윗 방향 화살표, 접히면 아랫방향 화살표 */}
{isActive ? '▲' : '▼'}
</button>
<ul
className={`text-white cursor-pointer w-32 absolute border border-black-300 shadow-lg transition-all duration-300 ease-out overflow-hidden rounded ${
isActive ? 'max-h-60 opacity-100' : 'max-h-0 opacity-0'
}`}
>
{/* 펼쳐지면 정렬 기준 항목들이 보이게 */}
{isActive &&
sortByList.map((item) => (
<li
key={item}
className='cursor-pointer w-full text-black-900 bg-white border border-black-300 hover:bg-gray-500'
// 각 항목을 클릭하면 해당하는 항목에 따라 굿즈 정렬
onClick={() => setSortBy(item)}
>
{item}
</li>
))}
</ul>
</div>
</>
);
}
GoodsList (정렬 로직)
더보기
useEffect(() => {
if (sortBy === '낮은가격순') {
setSortedGoods(goods.sort((a, b) => a.price - b.price));
console.log(sortedGoods);
}
if (sortBy === '높은가격순') {
setSortedGoods(goods.sort((a, b) => b.price - a.price));
}
if (sortBy === '이름순') {
setSortedGoods(
// 굿즈 이름이 한글임
goods.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)),
);
}
if (sortBy === '최신순') {
setSortedGoods(
goods.sort(
(a, b) =>
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
),
);
}
}, [sortBy]);
DropDownButton에서 soryBy (정렬 기준)을 변경하면 그에 맞춰 굿즈를 정렬
결과
'최종 프로젝트 (Voyage-X)' 카테고리의 다른 글
최종 프로젝트 - Supabase 정렬 기능 (0) | 2024.08.03 |
---|---|
최종 프로젝트 - react-query로 데이터 가져오기 (0) | 2024.08.03 |
최종 프로젝트 UI 작업 (굿즈샵 페이지 1차 UI) (0) | 2024.07.25 |
2024/07/18 TIL (0) | 2024.07.18 |
2024/07/17 TIL (0) | 2024.07.17 |