In this tutorial, we will dive into the concept of nested routing in Next.js. Nested routing allows us to create a hierarchical URL structure by nesting routing files within directories. This is a powerful feature that makes your URL structure more organized and intuitive.
By the end of this tutorial, you will be able to create nested routes in a Next.js application, understand how URL paths map to the file system, and use dynamic routes to handle a variety of URL structures.
Prior to starting this tutorial, you should have a basic understanding of JavaScript and React. Familiarity with Next.js would be beneficial but is not required.
Nested routing in Next.js is straightforward. Next.js uses a file-based routing system where the file structure in the pages
directory corresponds to the URL structure. Let's explore this concept with clear examples and best practices.
Start by creating a new directory within the pages
directory. Name it blog
.
Within the blog
directory, create a file named index.js
. This will serve as the default route for /blog
.
Now, create a new file in the blog
directory named post.js
. This will serve as the route for /blog/post
.
Now, if you navigate to /blog
in your browser, it will render the component in blog/index.js
. If you navigate to /blog/post
, it will render the component in blog/post.js
.
Next.js also supports dynamic routes, which are routes that can change based on data.
To create a dynamic route, name the file or directory with square brackets. For example, pages/blog/[id].js
matches /blog/1
, /blog/2
, etc.
In the component, you can access the dynamic part of the URL with the useRouter
hook from next/router
.
Here are some practical examples to illustrate the concepts we've discussed.
// pages/blog/index.js
export default function Blog() {
return <h1>This is the blog index page</h1>;
}
// pages/blog/post.js
export default function Post() {
return <h1>This is a blog post</h1>;
}
// pages/blog/[id].js
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
// The id is accessible through router.query.id
return <h1>This is blog post #{router.query.id}</h1>;
}
In this tutorial, we learned how to create nested routes in a Next.js application. We learned that the file structure in the pages
directory corresponds to the URL structure, and how to create dynamic routes that can change based on data.
Your next steps could involve exploring more complex routing scenarios, such as optional dynamic routes, catch-all routes, and API routes.
Exercise: Create a nested route for a /products
page, where each product has its own page at /products/[id]
.
Exercise: Create a nested route for a user profile page at /users/[username]
, where [username]
is dynamic.
Exercise: Create a catch-all route that matches any URL and displays the URL path on the page.
Remember, practice is key when it comes to getting comfortable with new concepts. Happy coding!