Next.js Dynamic Routing: How to Handle Multiple Routes at the Root
Directory structure
pages/index.js
import Link from "next/link";
const Home = () => {
return (
<div>
<Link href="/[dynamic]/[id]" as="/post/1">
<a>post 1</a>
</Link>
<br />
<br />
<Link href="/[dynamic]/[id]" as="/post/2">
<a>post 2</a>
</Link>
</div>
);
};
export default Home;
pages/[dynamic]/[id].js
import { useRouter } from "next/router";
import Link from "next/link";
const DynamicPage = () => {
const router = useRouter();
const {
query: { dynamic, id }
} = router;
return (
<div>
<Link href="/">
<a>Home</a>
</Link>
<p>
Rota: /{dynamic}/{id}
</p>
</div>
);
};
export default DynamicPage;
styles/style.css
body {
background-color: #7812e6;
}
a {
color: floralwhite;
}
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true
};
module.exports = nextConfig;
package.json
{
"name": "nextjs-dynamic-routing",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "9.5.0",
"next-router": "1.3.6",
"react": "16.8.6",
"react-dom": "16.8.6"
},
"license": "ISC",
"keywords": [],
"description": ""
}
In this guide, we will explore the process of handling multiple dynamic routes at the root level in Next.js. We will discuss the use of the <Link> component and the as prop, as well as how to extract dynamic route parameters using the useRouter hook. By the end of this guide, you will have a solid understanding of dynamic routing in Next.js.
Next.js dynamic routing tutorial
How to implement dynamic routes in Next.js
To implement dynamic routes in Next.js, you can use the <Link> component and the as prop, and extract dynamic route parameters using the useRouter hook. Here's an example of how to implement dynamic routes in Next.js:
Create a new page component for each dynamic route you want to implement. For example, if you have a blog, you might have a [id].js page for each blog post.
In the file for each page component, add a unique export that specifies the dynamic route.
In the getStaticPaths function, specify the paths for each dynamic route by returning an object with a paths property that contains an array of objects, each representing a single path.
In the getStaticProps function, fetch the data for the corresponding page based on the params passed in the context.
In the main layout file, use the <Link> component to link to the dynamic routes. Use the as prop to specify the dynamic path and pass in the id as a variable.
To access the dynamic parameters in the page component, you can use the useRouter hook from the next/router package.
OUT-PUT
How to loop through object of objects in JavaScript?
loop through object javascript | How will you loop through this array of objects in JavaScript?