Next.js / Routing in Next.js
Using dynamic routing in Next.js
In this tutorial, we will delve into dynamic routing in Next.js. We will create routes with dynamic path segments and learn how to handle a variable number of routes with a single…
Section overview
5 resourcesUnderstanding different routing concepts in Next.js, including dynamic routing.
1. Introduction
In this tutorial, we will explore dynamic routing in Next.js, a powerful feature that allows you to create pages with dynamic path segments. Our goal is to understand how to handle a variable number of routes using a single file.
By the end of this tutorial, you will learn:
- How to create dynamic routes in Next.js
- How to generate links to these routes
- How to fetch data based on the dynamic part of the route
Prerequisites:
- Basic knowledge of React.js
- Basic knowledge of Next.js
- Familiarity with JavaScript and Node.js
2. Step-by-Step Guide
Next.js allows you to create dynamic routes by adding brackets [] in the page filename. A file named pages/post/[id].js will match any route in the form of /post/*.
Creating a Dynamic Route
Let's create a dynamic route for a blog post:
- Create a new file called
[id].jsin thepages/postdirectory. - In this file, export a React component.
Here’s the basic structure of our page:
// pages/post/[id].js
function Post() {
return <h1>Post</h1>
}
export default Post
This page will now match any route that looks like /post/*.
Linking to a Dynamic Route
To link to a dynamic route, you’ll use the next/link package, which provides a Link component.
Let's create a link to our post:
import Link from 'next/link'
function Home(){
return (
<div>
<Link href="/post/1">
<a>Go to Post 1</a>
</Link>
</div>
)
}
export default Home
Fetching Data for Dynamic Route
In a dynamic page, you can fetch data based on the dynamic part of the page, using the getInitialProps function:
// pages/post/[id].js
import fetch from 'node-fetch'
function Post({ post }) {
return <h1>{post.title}</h1>
}
Post.getInitialProps = async ({ query }) => {
const res = await fetch(`https://api.example.com/posts/${query.id}`)
const post = await res.json()
return { post }
}
export default Post
In this example, getInitialProps receives a context object with a query property, which contains the dynamic segments of the route.
3. Code Examples
Example 1: Dynamic Route
// pages/post/[id].js
function Post() {
return <h1>Post</h1>
}
export default Post
This code creates a dynamic route that matches any route like /post/*
Example 2: Link to Dynamic Route
// pages/index.js
import Link from 'next/link'
function Home(){
return (
<div>
<Link href="/post/1">
<a>Go to Post 1</a>
</Link>
</div>
)
}
export default Home
This code creates a link to our dynamic route /post/1
Example 3: Fetching Data for Dynamic Route
// pages/post/[id].js
import fetch from 'node-fetch'
function Post({ post }) {
return <h1>{post.title}</h1>
}
Post.getInitialProps = async ({ query }) => {
const res = await fetch(`https://api.example.com/posts/${query.id}`)
const post = await res.json()
return { post }
}
export default Post
This code fetches data for our dynamic route based on the id segment.
4. Summary
In this tutorial, we learned how to create dynamic routes in Next.js, how to link to them, and how to fetch data based on the dynamic part of the route. The next steps would be to learn about static generation and server-side rendering in Next.js. You can find more about these topics in the Next.js documentation.
5. Practice Exercises
- Create a dynamic route for a user profile page. The route should be in the format
/user/[username]. - Create a link to user profile page from the home page.
- Fetch user data from an API based on the
usernamesegment of the route.
Remember to test your code after each step to make sure everything is working as expected. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article