DevFlow

Dev Overflow

How to dynamically render components based on URL params with the Next.js App Router?

clock icon

asked 10 months ago

message

1 Answers

eye

1 Views

I'm working on a Next.js project using the new App Router, and I want to dynamically render different components based on the URL parameters. I can't seem to get the dynamic routing to work properly. Here's what I'm trying to do:

I have a pages directory set up like this:

/app
  /[category]
    /[id]
      page.js

I want to load different components based on the category and id params. For example:

  • /app/blog/123 should load the BlogPost component.
  • /app/user/456 should load the UserProfile component.

My page.js currently looks like this:

import BlogPost from '@/components/BlogPost';
import UserProfile from '@/components/UserProfile';
import { useRouter } from 'next/router';

export default function Page() {
  const router = useRouter();
  const { category, id } = router.query;

  // This isn't working correctly
  if (category === 'blog') {
    return <BlogPost id={id} />;
  } else if (category === 'user') {
    return <UserProfile id={id} />;
  } else {
    return <div>Not Found</div>;
  }
}

But it's not rendering anything when I navigate to /app/blog/123. What am I missing? How can I properly set this up with the Next.js App Router?

 

 

 

1 Answers

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.

Top Questions