Dynamic routing in Next.js allows you to create flexible and scalable URL structures based on dynamic segments. Instead of defining static routes, you can use dynamic route parameters to handle different pages dynamically.
In Next.js, dynamic routes are defined using square brackets ([]) in the file name inside the pages directory.
Example: Dynamic Product Page
Let's say we have a product page where the product ID changes dynamically. We can create a file:
/pages/products/[id].tsx
Inside this file, we fetch the dynamic id using useRouter:
import { useRouter } from 'next/router';
const ProductPage = () => {
const router = useRouter();
const { id } = router.query; // Get dynamic ID from URL
return (
<div>
<h1>Product ID: {id}</h1>
<p>Details about product {id}...</p>
</div>
);
};
export default ProductPage;
Navigating to a Dynamic Route
You can navigate dynamically using router.push or <Link>:
import Link from 'next/link';
const ProductList = () => {
return (
<div>
<h1>Products</h1>
<ul>
<li><Link href="/products/1">Product 1</Link></li>
<li><Link href="/products/2">Product 2</Link></li>
</ul>
</div>
);
};
export default ProductList;
To handle multiple dynamic segments, use catch all routes by adding three dots (...) inside brackets:
/pages/products/[...slug].tsx
Inside the file:
import { useRouter } from 'next/router';
const ProductDetails = () => {
const router = useRouter();
const { slug } = router.query;
return <h1>Product Path: {JSON.stringify(slug)}</h1>;
};
export default ProductDetails;
This allows URLs like:
/products/shoes/nike
/products/electronics/phones/apple
Dynamic routing in Next.js makes it easy to build flexible URL structures for products, blog posts and user profiles. With catch all routes, you can handle complex URL patterns efficiently.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.