The issue lies in the use of the useRouter()
hook within the App Router. In the App Router, you should be using the params
object that's passed directly to the page or layout instead of relying on useRouter()
.
Here’s how you can rewrite your page.js
:
import BlogPost from '@/components/BlogPost';
import UserProfile from '@/components/UserProfile';
export default function Page({ params }) {
const { category, id } = params;
if (category === 'blog') {
return <BlogPost id={id} />;
} else if (category === 'user') {
return <UserProfile id={id} />;
} else {
return <div>Not Found</div>;
}
}
The params
object is automatically injected by Next.js when using the App Router, and it contains the dynamic segments from the URL. This approach is more aligned with the new App Router's pattern, where you receive params
as a prop directly.
Additionally, ensure that your directory structure follows the correct convention and that you’ve correctly set up your dynamic segments:
/app
/[category]
/[id]
page.js
This should now correctly render the BlogPost
or UserProfile
component based on the category
and id
parameters in the URL.