Dynamic URL not working
Unanswered
French Lop posted this in #help-forum
French LopOP
hey so im trying to have URL Parameter matching in next.js
my file path is
and this is my code
however i get a 404 whenever i go any random
my file path is
frontend\src\app\pages\product\[category]\[productId].tsxand this is my code
import { useRouter } from 'next/router';
function ProductPage() {
const router = useRouter();
const { category, productId } = router.query;
return (
<div>
<h2>Product Details</h2>
<p>Category: {category}</p>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductPage;however i get a 404 whenever i go any random
15 Replies
@French Lop hey so im trying to have URL Parameter matching in next.js
my file path is `frontend\src\app\pages\product\[category]\[productId].tsx`
and this is my code
ts
import { useRouter } from 'next/router';
function ProductPage() {
const router = useRouter();
const { category, productId } = router.query;
return (
<div>
<h2>Product Details</h2>
<p>Category: {category}</p>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductPage;
however i get a 404 whenever i go any random
Are you trying to use the app router or the pages router
If you use the app router that is not how you define a route
If you use the pages router it is src/pages not src/app/pages
French LopOP
oh i see
im currently using src/app/mypagefolder/page.tsx
is that the problem
Then the path needs to be [productId]/page.tsx not [productId].tsx
Also you need to use useParams() for that if you want to use client components, or the params prop if you want to use server components
next/router doesn’t work in the app router
French LopOP
got it. thanks!
let me try it
Blue Mockingbird
Quick question about this; would the params prop be passed in for client components? and can we use useParams() for server components? Or is it a strict delineation? thanks
Blue Mockingbird
Ah, you answered my question. Delineation was just me trying to clarify if it was one or the other. So it would be fine for me to use the params prop on both client/server comp? or is that not best practice
i would say it is not good practice to make your page component a client component due to reasons unrelated to this, but if your page component is a client component you can still use the params props just fine