Router์ outlet ์์ฑ์ ์ด์ฉํ์ฌ ์ฌ์ด๋๋ฐ ํญ ํด๋ฆญ์ ๋ด์ฉ ๋ฐ์ค์ ํญ์ ๋ฐ๋ฅธ ๋ค๋ฅธ ๋ด์ฉ๋ค์ด ๋ณด์ฌ์ง๋ ๊ฒ๊น์ง๋ ๊ตฌํ์ ํ๋๋ฐ ๋ฌธ์ ๋ ๊ด๋ฆฌ์์ฉ๊ณผ ๊ณ ๊ฐ์ฉ์ ์ฌ์ด๋๋ฐ ํญ ํ์ดํ์ด ์๋ก ๋ฌ๋ผ์ผ ํ๋ค๋ ์ ์ด๋ค.
๊ทธ๋์ ๋ด๊ฐ ์ด๋ฅผ ๊ตฌํํ๊ณ ์ ํ๋ ๋ฐฉ์์
useLocation().pathname
์ ์ผํญ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ์ฌ route path๊ฐ/client/mypage
๋ก ์์ํ ๋๋ ๊ณ ๊ฐ์ฉ, ์ด์ธ์๋ ๊ด๋ฆฌ์์ฉ ๋ด์ฉ์ด ๋ณด์ฌ์ง๋๋ก ์ฒ๋ฆฌํ๋ ๊ฒ์ด๋ค.
๊ทผ๋ฐ ๋ฌธ์ ๋
/client/mypage
์ผ ๋ ๊ณ ๊ฐ์ฉ ํญ ๋ด์ฉ์ด ๋ณด์ฌ์ง๊ธฐ ํ๋๋ฐ ์ด ๋ ํญ ํ์ดํ ์ค ํ๋๋ฅผ ํด๋ฆญํ๋ฉด/client/mypage/info
์ด๋ฐ ์์ผ๋ก route path๊ฐ ๋ณ๊ฒฝ๋๋ฏ๋ก ์ฌ์ด๋๋ฐ๊ฐ ๊ณ ๊ฐ์ฉ์ด ์๋ ๊ด๋ฆฌ์์ฉ ํญ ํ์ดํ๋ค๋ก ๋ณ๊ฒฝ๋์๋ค.๐ฅฒ
route path๋ฅผ
/client/mypage
์๋ ๊ฒ ๋ค ๋น๊ตํ ํ์๊ฐ ์๊ณ , route path์ client๊ฐ ๋ค์ด๊ฐ๋ฉด ๊ณ ๊ฐ์ฉ, admin์ด ๋ค์ด๊ฐ๋ฉด ๊ด๋ฆฌ์์ฉ ํญ์ ๋ณด์ฌ์ฃผ๋ฉด ๋๋ค.
/client/mypage/myinfo
์ด๋ฉดconsole.log(useLocation().pathname)
// /client/mypage/myinfo
split("/")
์ผ๋ก ๋๋๋ฉดconsole.log(useLocation().pathname.split('/'))`
// ['', 'client', 'mypage', 'myinfo']
const pathName = useLocation().pathname.split("/")[1]
console.log(pathName) // client or admin
์ฆ, ๋ณ์ pathName์๋ client
๋๋ admin
๊ฐ์ด ๋ด์์๊ฒ ๋๋ค.client
์ admin
์ด key
์ธ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.const Tabs = { client: clientTabs, admin: adminTabs};
pathName
(client
๋๋ admin
)์ Tabs์ key
๋ก ๋ฃ์ด ์ด์ ํด๋นํ๋ ๊ฐ์ธ ๋ฏธ๋ฆฌ ์ง์ ํด๋ ํญ ๋ฐฐ์ด์ map()
๋๋ฆฌ๋ฉด ๋๋ค.{Tabs[pathName].map((tab, idx) => {
return (
// ~~
);
})}
// ์ ์ฒด ์ฝ๋์ฐ
// MySideBar.js
import React, { useState } from "react";
import styled from "styled-components";
import { NavLink, useLocation } from "react-router-dom";
import SidebarItem from "../molecules/SidebarItem";
const MySideBar = () => {
const paths = useLocation().pathname;
// const pathName = useLocation().pathname; <- ๊ธฐ์กด ์๋ฌ ์ฝ๋
const pathName = useLocation().pathname.split("/")[1];
const clientTabs = [
{ name: "๋ด ์ ๋ณด", path: "/client/mypage/myinfo" },
{ name: "์์ฝ ์กฐํ", path: "/client/mypage/rez" },
{ name: "์ด์ ์์ฝ ์กฐํ", path: "/client/mypage/pastrez" },
{ name: "๋ด ๋ฆฌ๋ทฐ ๋ณด๊ธฐ", path: "/client/mypage/review" },
];
const adminTabs = [
{ name: "๋ด ์ ๋ณด", path: "/admin/mypage/myinfo" },
{ name: "์บ ํ์ฅ ๋ฑ๋ก ๋ฐ ๊ด๋ฆฌ", path: "/admin/mypage/post" },
{ name: "์บ ํ์ฅ ์์ฝ ๊ด๋ฆฌ", path: "/admin/mypage/rez" },
{ name: "์บ ํ์ฅ ๋ฆฌ๋ทฐ ๊ด๋ฆฌ", path: "/admin/mypage/review" },
];
// ๊ฐ์ฒด๋ก ์ฒ๋ฆฌ
const Tabs = {
client: clientTabs,
admin: adminTabs,
};
return (
<SideBarContainer>
{/* ๊ธฐ์กด ์๋ฌ ์ฝ๋ (์ผํญ ์ฐ์ฐ์ ํ์ฉ) ->
{(pathName === "/client/mypage/" ? clientTabs : adminTabs) */}
{Tabs[pathName].map((tab, idx) => {
return (
<NavLink to={tab.path} key={idx}>
<SidebarItem
tab={tab}
isActive={paths === tab.path ? true : false}
/>
</NavLink>
);
})}
</SideBarContainer>
);
};
export default MySideBar;