Jwt Token
November 17, 2024
In Next.js, you can handle multiple parameters in dynamic routes by using file-based routing with square brackets to capture those parameters.
Let's say you have a dynamic route with two parameters: category
and id
.
File-based routing structure:
To create a route like /products/:category/:id
, you would create a file path like:
pages/products/[category]/[id].js
Accessing the parameters:
In the [category]/[id].js
file, you can use Next.js's useRouter
hook to access the route parameters.
Here’s how you can set it up:
// pages/products/[category]/[id].js
import { useRouter } from 'next/router';
const ProductPage = () => {
const router = useRouter();
const { category, id } = router.query; // Access the category and id parameters
return (
<div>
<h1>Category: {category}</h1>
<h2>Product ID: {id}</h2>
</div>
);
};
export default ProductPage;
router.query
will contain an object where category
and id
are the dynamic segments from the URL./products/electronics/123
, category
will be "electronics"
and id
will be "123"
.If you want to handle even more dynamic segments or a variable number of parameters, you can use the "catch-all" syntax.
For example, if you wanted to catch routes like /products/category/1/subcategory/2
, you could use:
// pages/products/[...params].js
import { useRouter } from 'next/router';
const ProductPage = () => {
const router = useRouter();
const { params } = router.query;
// params is an array
return (
<div>
<h1>Parameters:</h1>
<pre>{JSON.stringify(params, null, 2)}</pre>
</div>
);
};
export default ProductPage;
In this case, params
will be an array like ["category", "1", "subcategory", "2"]
.
[param]
files.useRouter
to access the parameters.[...params].js
) for a variable number of dynamic parameters.