ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฌธ์ œ

ํŠน์ • ํŽ˜์ด์ง€์— ๋“ค์–ด๊ฐ”์„ ๊ฒฝ์šฐ, ์กฐ๊ฑด๋ถ€ ๋žœ๋”๋ง์„ ํ•ด์ฃผ๊ธฐ ์œ„ํ•ด์„œ 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 V6 check if path matches a pattern

I'm trying to check a "/admin/posts/new" to "/admin/*" in react-router v6. I found that there is a matchRoutes function import { useLocation } from "react-router"; const { pathname } = useLocation...

stackoverflow.com

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;
  };
๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
TAG
more
ยซ   2024/10   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ