-
Notifications
You must be signed in to change notification settings - Fork 2
fix: tab 필터링 searchParams 기반으로 변경, 새로고침해도 필터링 유지 #243
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hajiiiin
wants to merge
3
commits into
develop
Choose a base branch
from
fix/code-refactoring
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| "use client"; | ||
|
|
||
| import { createContext, useContext, useEffect, useRef, useState } from "react"; | ||
| import { useSearchParams, useRouter, usePathname } from "next/navigation"; | ||
|
|
||
| type MainTabContextType = { | ||
| activeIndex: number; | ||
| setActiveIndex: (index: number) => void; | ||
| addTabRefs: (index: number, ref: HTMLLIElement | null) => void; | ||
| sliderStyle: { width: number; translateX: number }; | ||
| }; | ||
|
|
||
| const MainTabContext = createContext<MainTabContextType | null>(null); | ||
|
|
||
| function useTabContext() { | ||
| const context = useContext(MainTabContext); | ||
| if (!context) { | ||
| throw new Error("Tab compound components must be used within a Tab.Root"); | ||
| } | ||
| return context; | ||
| } | ||
|
|
||
| // Tab의 props | ||
| type MainTabProps = { | ||
| children: React.ReactNode; | ||
| category?: React.ReactNode; // 카태고리 버튼 | ||
| targetIndex?: number; // 클릭 시 카테고리가 나와야 할 index | ||
| gap?: string; // 탭과 카테고리의 간격 | ||
| }; | ||
| // Tab 루트 컴포넌트 | ||
| export default function MainTab({ children, category, targetIndex, gap = "gap-4" }: MainTabProps) { | ||
| const searchParams = useSearchParams(); | ||
| const router = useRouter(); | ||
| const pathname = usePathname(); | ||
|
|
||
| // 현재 활성화된 탭의 인덱스 | ||
| const [activeIndex, setActiveIndex] = useState(0); | ||
| // 슬라이더의 길이 및 X축 이동거리 | ||
| const [sliderStyle, setSliderStyle] = useState({ width: 0, translateX: 0 }); | ||
| // 탭들의 ref | ||
| const tabRefs = useRef<(HTMLLIElement | null)[]>([]); | ||
|
|
||
| // URL에서 `type` 값을 읽어 `activeIndex` 업데이트 (뒤로 가기, 새로고침 대응) | ||
| useEffect(() => { | ||
| const currentType = searchParams.get("type") || "DALLAEMFIT"; | ||
| const selectedIndex = SERVICE_TABS.findIndex((t) => t.type === currentType); | ||
|
|
||
| if (selectedIndex !== -1 && selectedIndex !== activeIndex) { | ||
| setActiveIndex(selectedIndex); | ||
| } | ||
| }, [searchParams]); | ||
|
|
||
| useEffect(() => { | ||
| if (!tabRefs.current.length) return; // 아직 ref 배열이 비어 있다면 패스 | ||
| // 현재 활성화 된 Tab | ||
| const activeTab = tabRefs.current[activeIndex]; | ||
| if (activeTab) { | ||
| const width = activeTab.offsetWidth; | ||
| // 활성 탭 이전 탭들의 누적 offsetWidth를 계산. gap인 12px을 더해준다. | ||
| const offsetLeft = tabRefs.current | ||
| .slice(0, activeIndex) | ||
| .reduce((acc, el) => acc + (el?.offsetWidth || 0) + 12, 0); | ||
| setSliderStyle({ width, translateX: offsetLeft }); | ||
| } | ||
| }, [activeIndex]); | ||
|
|
||
| // context에 전달할 값들 | ||
| const contextValue = { | ||
| activeIndex, | ||
| setActiveIndex: (index: number) => { | ||
| setActiveIndex(index); | ||
|
|
||
| // 📌 URL도 함께 업데이트 (뒤로 가기 대응) | ||
| const tabType = SERVICE_TABS[index].type; | ||
| router.push(`${pathname}?type=${tabType}`); | ||
| }, | ||
| addTabRefs: (index: number, ref: HTMLLIElement | null) => { | ||
| tabRefs.current[index] = ref; | ||
| }, | ||
| sliderStyle, | ||
| }; | ||
| return ( | ||
| <MainTabContext.Provider value={contextValue}> | ||
| <div className={`flex flex-col ${gap}`}> | ||
| <div className="relative"> | ||
| {/* 탭 */} | ||
| <ul className="flex gap-3 text-lg font-semibold text-gray-400">{children}</ul> | ||
| {/* 슬라이더 */} | ||
| <div | ||
| style={{ | ||
| width: sliderStyle.width, | ||
| transform: `translateX(${sliderStyle.translateX}px)`, | ||
| }} | ||
| className={`absolute bottom-0 h-[2px] bg-gray-900 transition-all duration-300`} | ||
| /> | ||
| </div> | ||
| {targetIndex === activeIndex && <div>{category}</div>} | ||
| </div> | ||
| </MainTabContext.Provider> | ||
| ); | ||
| } | ||
|
|
||
| // 탭 아이템 | ||
| type ItemProps = { | ||
| index: number; | ||
| children: React.ReactNode; | ||
| }; | ||
| MainTab.Item = function ({ index, children }: ItemProps) { | ||
| const { activeIndex, setActiveIndex, addTabRefs } = useTabContext(); | ||
|
|
||
| return ( | ||
| <li | ||
| onClick={() => setActiveIndex(index)} | ||
| ref={(el) => { | ||
| addTabRefs(index, el); | ||
| }} | ||
| // 활성화된 탭이면 text의 색을 변경 | ||
| className={`${activeIndex === index && "text-gray-900"} mb-1 flex cursor-pointer items-center gap-1 transition-colors duration-300`} | ||
| > | ||
| {children} | ||
| </li> | ||
| ); | ||
| }; | ||
|
|
||
| // 📌 서비스 탭 리스트 (예제) | ||
| const SERVICE_TABS = [ | ||
| { name: "달램핏", type: "DALLAEMFIT" }, | ||
| { name: "워케이션", type: "WORKATION" }, | ||
| ]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,9 @@ | ||
| "use client"; | ||
|
|
||
| import { useState, useEffect, useCallback } from "react"; | ||
| import { useSearchParams } from "next/navigation"; | ||
| import CategoryButton from "@/components/CategoryButton"; | ||
| import Tab from "@/components/Tab"; | ||
| import MainTab from "@/components/MainTab"; | ||
| import Dalaemfit from "@/images/dalaemfit.svg"; | ||
| import Workation from "@/images/workation.svg"; | ||
|
|
||
|
|
@@ -23,26 +24,35 @@ type ServiceTabProps = { | |
| isFilteringLoading?: boolean; // 필터링 중인지 판단하는 변수 | ||
| }; | ||
|
|
||
| export default function ServiceTab({ searchParams, onCategoryChange, isFilteringLoading }: ServiceTabProps) { | ||
| const [selectedTab, setSelectedTab] = useState<"DALLAEMFIT" | "WORKATION">( | ||
| () => (searchParams.get("type") || "DALLAEMFIT") as "DALLAEMFIT" | "WORKATION", | ||
| ); | ||
| const [selectedCategory, setSelectedCategory] = useState<string>("전체"); | ||
| export default function ServiceTab({ onCategoryChange, isFilteringLoading }: ServiceTabProps) { | ||
| const searchParams = useSearchParams(); | ||
|
|
||
| // URL이 변경되었을 때 필터링 로딩 상태 해제 | ||
| useEffect(() => { | ||
| if (!isFilteringLoading) return; | ||
| const [selectedTab, setSelectedTab] = useState<string>( | ||
| () => SERVICE_TABS.find((t) => t.type === searchParams.get("type"))?.name || "DALLAEMFIT", | ||
| ); | ||
|
|
||
| const currentType = searchParams.get("type") || "DALLAEMFIT"; | ||
| setSelectedTab(currentType as "DALLAEMFIT" | "WORKATION"); | ||
| }, [searchParams, isFilteringLoading]); | ||
| const [selectedCategory, setSelectedCategory] = useState<string>( | ||
| () => CATEGORIES.find((c) => c.type === searchParams.get("type"))?.name || "전체", | ||
| ); | ||
|
|
||
| // searchParams 변경 감지해서 반영 | ||
| //searchParams 변경 감지해서 반영 | ||
| useEffect(() => { | ||
| const currentType = searchParams.get("type") || "DALLAEMFIT"; | ||
|
|
||
| if (currentType !== selectedTab) { | ||
| setSelectedTab(currentType as "DALLAEMFIT" | "WORKATION"); | ||
| console.log("선택된 타입: ", currentType); | ||
|
|
||
| if (currentType) { | ||
| const tabName = SERVICE_TABS.find((t) => t.type === currentType)?.name; | ||
|
|
||
| console.log("찾은 탭 이름1:", tabName); | ||
| console.log("selectedTab은? ", selectedTab); | ||
| if (tabName && tabName == selectedTab) { | ||
| setSelectedTab(tabName); | ||
| console.log("찾은 탭 이름2:", tabName); | ||
|
|
||
| // 📌 `handleTabChange` 실행 (중복 실행 방지됨) | ||
| handleTabChange(tabName); | ||
| } | ||
| } | ||
| }, [searchParams]); | ||
|
|
||
|
|
@@ -53,8 +63,12 @@ export default function ServiceTab({ searchParams, onCategoryChange, isFiltering | |
| const tabType = SERVICE_TABS.find((t) => t.name === tabName)?.type; | ||
| if (!tabType) return; | ||
|
|
||
| setSelectedTab(tabType as "DALLAEMFIT" | "WORKATION"); | ||
| // URL의 type 값을 가져와서 selectedTab 업데이트 | ||
| const currentType = searchParams.get("type") || tabType; // 없으면 클릭한 탭을 기본값으로 | ||
| console.log("핸들러 실행됨11:", currentType); | ||
| setSelectedTab(currentType); | ||
|
|
||
| setSelectedTab(tabType); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
setSelectedTab(currentType);
...
setSelectedTab(tabType);최종적으로 |
||
| onCategoryChange(tabType); | ||
| handleCategoryReset(); | ||
| }; | ||
|
|
@@ -77,7 +91,7 @@ export default function ServiceTab({ searchParams, onCategoryChange, isFiltering | |
|
|
||
| return ( | ||
| <> | ||
| <Tab | ||
| <MainTab | ||
| category={ | ||
| <CategoryButton | ||
| categories={CATEGORIES.map((c) => c.name)} | ||
|
|
@@ -93,7 +107,7 @@ export default function ServiceTab({ searchParams, onCategoryChange, isFiltering | |
| targetIndex={0} | ||
| > | ||
| {SERVICE_TABS.map((tabItem, idx) => ( | ||
| <Tab.Item key={tabItem.name} index={idx}> | ||
| <MainTab.Item key={tabItem.name} index={idx}> | ||
| <button | ||
| onClick={() => handleTabChange(tabItem.name)} | ||
| className="flex items-center" | ||
|
|
@@ -102,9 +116,9 @@ export default function ServiceTab({ searchParams, onCategoryChange, isFiltering | |
| {tabItem.name} | ||
| <tabItem.icon className="items-center" /> | ||
| </button> | ||
| </Tab.Item> | ||
| </MainTab.Item> | ||
| ))} | ||
| </Tab> | ||
| </MainTab> | ||
| </> | ||
| ); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
selectedTab 상태 관리가 일관되지 않습니다.
selectedTab이 탭 이름으로 초기화되지만 코드 일부분에서는 탭 타입으로 취급됩니다. 상태 관리의 일관성을 유지해야 합니다.📝 Committable suggestion