Routing
When a file is added to the directory it’s automatically available as a route.
The files inside the pages
directory can be used to define most common patterns.
Index routes
The router will automatically route files named index
to the root of the directory.
pages/index.js
→/
pages/blog/index.js
→/blog
Nested routes
The router supports nested files. If you create a nested folder structure files will be automatically routed in the same way still.
pages/blog/first-post.js
→/blog/first-post
pages/dashboard/settings/username.js
→/dashboard/settings/username
Dynamic route segments
To match a dynamic segment you can use the bracket syntax. This allows you to match named parameters.
pages/blog/[slug].js
→/blog/:slug
()pages/[username]/settings.js
→/:username/settings
(/foo/settings
)
A React component called Link
is provided to do this client-side route transition.
In the example above we have multiple links, each one maps a path (href
) to a known page:
/
→pages/index.js
/about
→pages/about.js
- →
pages/blog/[slug].js
You can also use interpolation to create the path, which comes in handy for . For example, to show a list of posts which have been passed to the component as a prop:
encodeURIComponent
is used in the example to keep the path utf-8 compatible.
Alternatively, using a URL Object:
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 thepages
directory./blog/[slug]
in this case.query
is an object with the dynamic segment.slug
in this case.
To access the router
object in a React component you can use or withRouter
.
In general we recommend using .
The router is divided in multiple parts:
Handle client-side navigations.