0
0
NextJSframework~30 mins

Dynamic routes with [param] in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic routes with [param] in Next.js
📖 Scenario: You are building a simple blog website using Next.js. Each blog post has a unique ID. You want to create pages that show the content of each post based on its ID in the URL.
🎯 Goal: Build dynamic routes using the [param] folder naming in Next.js to display blog post content based on the post ID from the URL.
📋 What You'll Learn
Create a data structure with blog posts and their content
Add a configuration variable for the default post ID
Create a dynamic route file using [id] folder naming
Fetch and display the blog post content based on the dynamic id parameter
💡 Why This Matters
🌍 Real World
Dynamic routes let websites show different content based on URL parts, like user profiles or product pages.
💼 Career
Understanding dynamic routing is essential for building modern web apps with Next.js, a popular React framework.
Progress0 / 4 steps
1
Create blog posts data
Create a constant called posts as an object with these exact entries: "1": "Welcome to Next.js!", "2": "Learning dynamic routes.", and "3": "Building cool apps."
NextJS
Need a hint?

Use a JavaScript object with string keys for post IDs and string values for content.

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

Use a constant string variable for the default post ID.

3
Create dynamic route component
Create a React functional component called PostPage that accepts a params object with an id property. Inside the component, get the post content from posts[params.id] or use posts[defaultPostId] if undefined. Return a <main> element with a <h1> showing "Post ID: " plus the id, and a <p> showing the post content.
NextJS
Need a hint?

Use the nullish coalescing operator ?? to provide a fallback post content.

4
Add dynamic route file structure
Create a file named app/posts/[id]/page.js and place the PostPage component code inside it. Export the component as default. This will enable dynamic routing based on the id parameter in the URL.
NextJS
Need a hint?

Dynamic route files in Next.js use square brackets around the parameter name in the folder or file name.