-
[react] react-router-dom Outlet으로 Tab메뉴 구현하기프론트엔드 개발자가 될거야./react 2023. 2. 8. 13:45
이러한 메뉴를 Tab 메뉴라고 하는데
react-router-dom Outlet으로 구현하는 방법에 대해 포스팅하려고 한다.
예를들어 마이페이지를 탭메뉴로 구성한다면
1. Router.tsx
function Router() { return ( <BrowserRouter> <Routes> <Route path="/mypage" element={<MyPage />}> <Route path="profile" element={<ProfilePage />} /> <Route path="logout" element={<LogoutPage />} /> <Route path="setting" element={<SettingPage />} /> </Route> </Routes> </BrowserRouter> ); } export default Router;
먼저 Router에서 MyPage 컴포넌트의 자식들로 메뉴들을 넣어준다.
2. MyPage.tsx
function MyPage() { const profilesMatch = useMatch("/mypage/profile"); const logoutMatch = useMatch("/mypage/logout"); const settingMatch = useMatch("/mypage/googleOTP"); return ( <MyPageContainer> <MyPageWrapper> <MyPageMenu> <Tap isActive={profilesMatch !== null}> <Link to="/mypage/profile"> <div>프로필</div> </Link> </Tap> <Tap isActive={profilesMatch !== null}> <Link to="/mypage/profiles"> <div>로그아웃</div> </Link> </Tap> <Tap isActive={settingMatch !== null}> <Link to="/mypage/setting"> <div>설정</div> </Link> </Tap> </MyPageMenu> <Outlet /> </MyPageWrapper> </MyPageContainer> ); } export default MyPage;
Outlet을 이용하여 MyPage 컴포넌트에서 각 메뉴를 클릭하면 해당 컴포넌트가 나오도록 해준다.
또한 나는 styled-component로 css를 그리는데
sActive라는 props를 통해 클릭된 메뉴를 전달해주고 있다.react-router-dom의 useMatch를 이용하면 내가 현재있는 url이 내가 원하는 url에 있는지 true/false 값으로 알 수 있다.
이 값을 이용해서 isActive에 전달해주면 된다.
'프론트엔드 개발자가 될거야. > react' 카테고리의 다른 글
stacked card slider 구현하기(react, styled-component) (0) 2023.05.11 [이미지 업로드, 이미지 프리뷰] FileReader객체란? reader.onload 함수란? (feat. chatGPT 너 진짜 똑똑하다..) (2) 2023.02.16 로그인페이지에 헤더 안보이게 하기 (with. useLocation) (0) 2023.02.04 [MUI Table 커스텀하기] React, Styled-Componet, Material-UI, TypeScript에서 테이블 커스텀하기 (0) 2023.02.04 [react-query] react-query는 왜 써야할까? (0) 2023.01.24