🙆♂️
Next.jsで今いる画面のURLからPathを取得する方法
Next.jsにはuseRouterというhooksが用意されているのでそれを使うと良い。
やってみる
にアクセスした場合
const router = useRouter();
console.log(router.route) // => /profile
console.log(router.basePath) // =>
console.log(router.asPath) // => /profile/?test=1
console.log(router.locale) // => undefined
console.log(router.defaultLocale) // => undefined
console.log(router.domainLocales) // => undefined
console.log(router.events) // => {on: ƒ, off: ƒ, emit: ƒ}
console.log(router.pathname) // => /profile
まとめ
- パスだけ欲しい時には
pathname
- クエリも含めて欲しい時には
asPath
- 多言語化で処理を考える時には
locale
でごにょごにょ
で良さそう。
Discussion