React

React 에서 새로고침 시 탭이 첫 번째 항목으로 이동하는 문제 해결

아뵹젼 2022. 4. 10.
 const currentTab = () => {
    let path = window.location.pathname;
    console.log("경로", path);
    if (path === "/mypage") return 1;
    else if (path === "/mypage/my_comment") return 2;
    else if (path === "/mypage/my_interested_animal") return 3;
    else if (path === "/mypage/my_interested_board") return 4;
    else if (path === "/mypage/edit_info") return 5;
  };

  const [menu, setMenu] = useState(currentTab);

React에서 ul li 를 이용해 상단 탭을 구현했었다.

그리고 각 탭을 클릭할 시 해당하는 라우터로 이동하도록 하였다.

그런데 새로고침을 하면 라우터는 그대론데, 탭이 첫 번째 항목으로 초기화되는 문제가 발생했다.

 

이는 tab 을 useState(1) 으로 초기화 했기 때문이다.

따라서 해당 컴포넌트가 재렌더링 될 때마다 초기화 되었던 것이다.

 

 

 

이를 해결하기 위해 몇시간 동안 정말 많은 삽질을 했는데,,, 

처음에 방향을 잘못 잡아서 라우터 Redirect 쪽으로 계속 검색했었다ㅜㅜ

나는 문제의 원인을 분석하기 위해 깊은 사고를 하지 못하고, 하나에 꽂히면 잘못된 방향을 깊게 파고드는 안좋은 경향이 있는 것 같다... ㅠㅠ 

 

 

 

내가 해결할 수 있었던 solution 은 다음과 같다.

https://stackoverflow.com/questions/61199980/material-ui-tab-indicator-returns-back-to-the-first-tab-item-when-i-reload-the-p

 

Material-UI tab indicator returns back to the first tab item when i reload the page

I implemented material-ui tabs with react router. When i click on a tab, the tab indicator which is a blue line underneath the tab works as intended, it moves to which ever tab was pressed. The pro...

stackoverflow.com

 

 

tab 을 useState 로 초기화 할 때, 현재 url path 에 따라 결정하는 것이다.

 

 

내 코드에선 다음과 같다.

 const currentTab = () => {
    let path = window.location.pathname;
    console.log("경로", path);
    if (path === "/mypage") return 1;
    else if (path === "/mypage/my_comment") return 2;
    else if (path === "/mypage/my_interested_animal") return 3;
    else if (path === "/mypage/my_interested_board") return 4;
    else if (path === "/mypage/edit_info") return 5;
  };

  const [menu, setMenu] = useState(currentTab);

 

혹시 더 좋은 방법이 있다면 공유 해주세요,,,,

 

 

 

+ window.localStorage 를 사용하여 마지막으로 활성화된 탭을 저장하는 방법도 있더라..!

댓글