0
0
NextJSframework~30 mins

Dynamic route segments in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic Route Segments in Next.js
📖 Scenario: You are building a blog website using Next.js. Each blog post has a unique ID, and you want to create pages that show the content of each post dynamically based on the URL.
🎯 Goal: Create a dynamic route segment in Next.js to display blog post details based on the post ID from the URL.
📋 What You'll Learn
Create a data structure with blog posts and their details
Add a configuration variable for the default post ID
Use Next.js dynamic route segment to fetch the post ID from the URL
Display the blog post title and content dynamically on the page
💡 Why This Matters
🌍 Real World
Dynamic route segments let websites show different content pages based on URL parts, like user profiles or blog posts.
💼 Career
Understanding dynamic routes is essential for building modern web apps with Next.js, a popular React framework used in many companies.
Progress0 / 4 steps
1
Create blog posts data
Create a constant called posts that is an object with these exact entries: "1": { title: "First Post", content: "This is the first post." }, "2": { title: "Second Post", content: "This is the second post." }, and "3": { title: "Third Post", content: "This is the third post." }.
NextJS
Need a hint?

Use a constant object named posts with keys as strings "1", "2", and "3".

2
Add default post ID configuration
Create a constant called defaultPostId and set it to the string "1".
NextJS
Need a hint?

Define a constant defaultPostId with the value "1" as a string.

3
Create dynamic route component
Create a default exported React functional component called PostPage that uses the Next.js useRouter hook to get the postId from router.query. Use defaultPostId if postId is undefined. Then get the post data from posts[postId].
NextJS
Need a hint?

Use useRouter to get postId from router.query. Use ?? to fallback to defaultPostId.

4
Add dynamic route file and export
Create a file named [postId].jsx inside the app directory and place the PostPage component code inside it. Ensure the file exports the PostPage component as default.
NextJS
Need a hint?

Save this component in a file named [postId].jsx inside the app folder to enable dynamic routing.