Understanding Dynamic Routes in Next.js
Jul 26, 2023Dynamic routes in Next.js offer a powerful and flexible way to create pages where part of the path can vary. To define a dynamic route, you simply wrap the filename of the route in square brackets []
. Next.js then interprets this route as dynamic, allowing you to capture and use the variable part of the route in your component.
Creating Dynamic Routes
To illustrate this, let's look at an example where we want to create a page for different music genres, with the genre part being variable. The setup would look something like this:
// pages/[genre].tsx import { useRouter } from 'next/router' export default function Genre( ) { const router = useRouter() const { genre } = router.query return <h1>{genre}</h1> }
In the example above, we have a dynamic route defined by the [genre].tsx
file. To access the dynamic part of the route (i.e., the genre), we use the useRouter
hook from the next/router
package. This hook returns a router object, from which we can extract the query
object. The query
object contains key-value pairs where the key corresponds to the dynamic part of the route, and the value is the actual value in the URL.
Once the application is running, you can navigate to any URL like /rock
, /country
, or /pop
, and the value of the genre
will be displayed in an h1
tag.
Nested Dynamic Routes
Next.js also supports nested dynamic routes. Let's say we have a blog, and we want to create a route that displays a specific comment under a specific post. Here's how we might set that up:
// pages/post/[pid]/[comment].tsx import { useRouter } from 'next/router' export default function Comment( ) {const router = useRouter() const { pid, comment } = router.query console.log(pid, comment) // For the sake of simplicity, we're just returning a static text here return <p>Hello</p> }
In this scenario, pid
and comment
are dynamic parts of the route. By nesting the dynamic routes (i.e., placing the [comment].tsx
file inside a folder named [pid]
), we can capture multiple dynamic values from the URL.
When visiting a URL such as /post/123/456
, the console will log 123
and 456
, corresponding to pid
and comment
respectively.
Recap
Dynamic routes in Next.js, defined by wrapping part of the filename in square brackets []
, provide a flexible way to handle routes where part of the path can change. The useRouter
hook allows us to access these dynamic parts of the URL. By placing dynamic routes inside other dynamic routes, we can also handle complex routing scenarios with nested dynamic values.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed sapien quam. Sed dapibus est id enim facilisis, at posuere turpis adipiscing. Quisque sit amet dui dui.
Stay connected with news and updates!
Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.
We hate SPAM. We will never sell your information, for any reason.