Next.js はページという概念に基づいて、ファイルシステムに沿ったルーターを持っています。
pages ディレクトリにファイルが追加されたとき、ルートとして自動で使用可能になります。
pages ディレクトリ内のファイルは次の一般的なパターンで定義されます。
ルーターは index という名前のファイルをディレクトリのルートとしてルーティングします。
pages/index.js → /pages/blog/index.js → /blogルーターはネストされたファイルもサポートします。ネストされたフォルダ構造を作ると、内部に置かれたファイルも同じようにルーティングされます。
pages/blog/first-post.js → /blog/first-postpages/dashboard/settings/username.js → /dashboard/settings/username動的なセグメントにマッチさせたければブラケット記法を使うことができます。名前をつけたパラメータとのマッチが可能です。
pages/blog/[slug].js → /blog/:slug (/blog/hello-world)pages/[username]/settings.js → /:username/settings (/foo/settings)pages/post/[...all].js → /post/* (/post/2020/id/title)Check out the Dynamic Routes documentation to learn more about how they work.
Next.js のルーターは、シングルページアプリケーションのようにクライアントサイドでのページ間遷移が可能です。
このクライアントサイドでのページ遷移のために、Link という React コンポーネントが提供されています。
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/about">
<a>About Us</a>
</Link>
</li>
<li>
<Link href="/blog/hello-world">
<a>Blog Post</a>
</Link>
</li>
</ul>
)
}
export default Home
The example above uses multiple links. Each one maps a path (href) to a known page:
/ → pages/index.js/about → pages/about.js/blog/hello-world → pages/blog/[slug].jsAny <Link /> in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using Static Generation. The corresponding data for server-rendered routes is not prefetched.
You can also use interpolation to create the path, which comes in handy for dynamic route segments. For example, to show a list of posts which have been passed to the component as a prop:
import Link from 'next/link'
function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/blog/${encodeURIComponent(post.slug)}`}>
<a>{post.title}</a>
</Link>
</li>
))}
</ul>
)
}
export default Posts
encodeURIComponentis used in the example to keep the path utf-8 compatible.
Alternatively, using a URL Object:
import Link from 'next/link'
function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link
href={{
pathname: '/blog/[slug]',
query: { slug: post.slug },
}}
>
<a>{post.title}</a>
</Link>
</li>
))}
</ul>
)
}
export default Posts
Now, instead of using interpolation to create the path, we use a URL object in href where:
pathname is the name of the page in the pages directory. /blog/[slug] in this case.query is an object with the dynamic segment. slug in this case.React コンポーネント内で router オブジェクト にアクセスするには useRouter もしくは withRouter を使うことができます。
一般的に useRouter を使うことをお勧めします。
ルーターは複数のパーツに分かれています。