ํฐ์คํ ๋ฆฌ ๋ทฐ
react-router-dom(v6) path ๊ฒฝ๋ก์ ๋ง๊ฒ ์กฐ๊ฑด๋ถ ๋๋๋ง_matchPath
choi95 2022. 3. 26. 13:25๋ฌธ์
ํน์ ํ์ด์ง์ ๋ค์ด๊ฐ์ ๊ฒฝ์ฐ, ์กฐ๊ฑด๋ถ ๋๋๋ง์ ํด์ฃผ๊ธฐ ์ํด์ react-router-dom ๋ด matchPath()๋ฅผ ์ฌ์ฉํ์ฌ ๋ค์๊ณผ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ ๊ฒฝํ์ด ์์๋ค.
const TopNav = () => {
const navigate = useNavigate();
const location = useLocation();
const isAuthView = () => {
const currentPathname = location.pathname;
if (
matchPath(currentPathname, { path: "/login" }) ||
matchPath(currentPathname, { path: "/login" })
)
return true;
else return false;
};
if (isAuthView()) return null;
else
return (
( ... )
);
};
useLocation()์ ์ฌ์ฉํ์ฌ ํ์ฌ ํด๋ผ์ด์ธํธ ์ธก์์ ๋ผ์ฐํ ๋ path ๊ฒฝ๋ก๋ฅผ ๊ฐ์ ธ์ค๊ณ ์ง์ ๋ path ๊ฒฝ๋ก์ ์ผ์นํ๋์ง ์ฌ๋ถ๋ฅผ matchPath()๋ฅผ ํตํด ํ์ธํ ๋ค์ ๊ฒฐ๊ณผ๊ฐ์ ํ ๋๋ก ์กฐ๊ฑด๋ถ ๋๋๋ง์ ํด์ฃผ์๋ค.
ํ์ง๋ง ํด๋น ์ฝ๋ ํ ๋๋ก ๋ค๋ฅธ ํ๋ก์ ํธ ๋ด์์ ๋๊ฐ์ ๋ฐฉ์์ผ๋ก ๊ฒฝ๋ก ๋น๊ต๋ฅผ ํด ์ฃผ์๋๋, ์กฐ๊ฑด๋ถ ๋๋๋ง์ด ์ ๋๋ก ๋์๋์ง ์์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์๋ค.
๋ฌธ์ ํด๊ฒฐ
๊ตฌ๊ธ๋ง ํด๋ณธ ๊ฒฐ๊ณผ stackoverflow์์ ํด๋น ๋ฌธ์ ์ ๋ํ ๋ต์ ์ฐพ์ ์ ์์๋ค.https://stackoverflow.com/questions/61235191/react-router-v6-check-if-path-matches-a-pattern
react-router-dom ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ๋ฒ์ 6์ผ๋ก ์ ๋ฐ์ดํธ๋๋ฉด์ matchPath์ ์ฌ์ฉ ๋ฐฉ์์ด ๋ฌ๋ผ์ ธ์ ์ ๋๋ก ๋ ๊ฒฐ๊ณผ๋ฅผ ํ์ธํ ์ ์์๋ ๊ฒ์ด๋ค.
์๋๋ ๋ค์๊ณผ ๊ฐ์ด matchPath ์ฒซ ๋ฒ์งธ ์ธ์๋ก ํ์ฌ ๊ฒฝ๋ก๋ฅผ ๋ฃ์ด์ฃผ๊ณ ๋ ๋ฒ์งธ ์ธ์์๋ ๋น๊ต๋ ๊ฒฝ๋ก๋ฅผ ๊ฐ์ฒด๋ก ๋ฉํํ์๋ค.
matchPath(ํ์ฌ ๊ฒฝ๋ก, {path: ๋น๊ต ๊ฒฝ๋ก})
๋ฒ์ 6์ด์๋ถํฐ๋ ํด๋น ๋ฐฉ์์ด ์๋์ ๊ฐ์ด ๊ฐ์ฒด๋ก ๋งตํํ์ง ์๊ณ ๋ฐ๋ก ๋น๊ต ๊ฒฝ๋ก๋ฅผ ์ฒซ ๋ฒ์งธ ์ธ์์ ๋ฃ์ด์ฃผ๋ ๊ฒ์ ๋ฐ๋์๋ค.
matchPath(๋น๊ต ๊ฒฝ๋ก, ํ์ฌ ๊ฒฝ๋ก)
์ด๋ฅผ ํ ๋๋ก ๋ค์๊ณผ ๊ฐ์ด ํด๋น ์ฝ๋๋ฅผ ์์ ํ์๊ณ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์๋ค.
const isAuthView = () => {
const currentPathname = location.pathname;
if ( // ๋ก๊ทธ์ธ ๋ฐ ํ์๊ฐ์
ํ์ด์ง์ผ ๊ฒฝ์ฐ์ true ๊ฐ์ ๋ฆฌํด
matchPath("/login", currentPathname) ||
matchPath("/register", currentPathname)
)
return true;
else return false;
};