[Challenge] useRouter hook 만들기(with. react-router)

KoEunseo·2023년 3월 19일
0

challenge

목록 보기
9/9
import { useNavigate } from 'react-router-dom'

export const useRouter = () => {
  const router = useNavigate()

  return {
    currentPath: window.location.pathname,
    routeTo: (path: string) => router(path)
  }
}

window.location은 종종 사용했는데 .pathname은 뭘까? 이름만 봤을때는 현재의 라우팅 위치를 가져오는 것 같다. 현재 위치의 pathname이 왜 필요하냐면, 네비게이션은 현재 위치를 알려주는 css를 입히기 마련이기 때문. 실제로 아래와 같이 sidebar 컴포넌트에서 className을 삼항연산자로 리턴하는 것을 볼 수 있었다.

className={currentPath === element.path ? "sidebar selected" : "sidebar"}

.pathname

mdn doc
위치에 대한 url의 경로를 포함하는 문자열. 경로가 없다면 비어있다.
경로가 있다면 '/'뒤의 url 경로를 포함한다.

맨날 reload랑 replace href만 썼는데
location에도 많은 api들이 있구나... 😳

useNavigate

package.json

  "dependencies": {
    "@remix-run/router": "1.3.3",
    "react-router": "6.8.2"
  },
  "devDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },

저놈의 RemixRouter는 뭘까. react-router-dom이나 remix-run/router나 똑같은 것 같은데 remix-router는 v1.4.0이고 react-router는 v6.9.0이다.. 오잉?? 대체 뭐지?? npm 사이트에서 리포지토리 들어가면 똑같은 화면 나온다... 흠 내일 한번 둘다 깔아보고 뭐가 다른지 비교좀 해봐야겠다...

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글