DEV Community

Ashutosh
Ashutosh

Posted on

Next.js File Based Routing (Dynamic Routes and Navigation) (Part-2)

If you are new to this page, please follow the previous tutorials before proceeding further.

There is an administrator whose job is to maintain the web application. He can create, edit, delete application users. He does this regularly. He also wants to know how many users are added to the application every month or year. It means we need to update the same component but for different parameters. Here dynamic routing comes into the picture.

Under pages, create a new folder admin.
Create a new folder "users" under admin.
create a file [...users].js.

Your directory structure should look like the below illustration.

[...users].js file in Next.js represents the complex Dynamic path. And it will catch all the routes like /admin/users/2021/ or /admin/users/2021/03/.

Update the contents of the file with the following:

import { useRouter } from 'next/router';



function UsersListPage() {
  const router = useRouter();
  const params  = router.query.users || [];

  return (
    <div>List all the users for { params.join('/') }</div>
  )
}


export default UsersListPage;
Enter fullscreen mode Exit fullscreen mode

Now visit http://localhost:3000/admin/users/2021, you will see "List all the users for 2021".

And then Visit http://localhost:3000/admin/users/2021/03/, you will see "List all the users for 2021/03".

we have created individual pages. At present, there is no way to navigate between the pages. We have to type the URL on the browser and, then we see the contents of that page.

Let's add Navigation to the Home page.

Open the index.js file and add the following:

import Link from 'next/link';
function HomePage() {
  return (
    <div>
      This is the root of the application
      <ul>
        <li>
          <Link href="/contact">Contact</Link>
        </li>
        <li> 
          <Link href="/user/profile">Profile</Link>
        </li>
      </ul>
    </div>
  )
}
export default HomePage;
Enter fullscreen mode Exit fullscreen mode

Take a look at the first line. We import Link not { Link } from the next/router. It is because Link is the default object of next/router. And for navigation between the pages, we use Link, not the anchor tags ("").

We can use anchor tags as well and, it will work fine. You can test it by replacing the Link with the anchor tag. But we are doing it for a purpose. If we use the anchor tag and then click on the Contact, we can see the contents of the page. But anchor tag always generates a new HTTP request to the server. It implies if we have the state, then it will be lost during the transition. You can observe it by seeing the circle on the browser tab when you click on the Contact link.

If we want to preserve the state of the application, Next.js has a Link tag. It will not generate the new HTTP request every time the page loads and saves the web application state. Link tag also prefetches the data from the server as we hover to it.

Navigating Dynamic Routes
In our previous articles, we created dynamic routes for the users (/user/1, /user/2 where 1 and 2 are the user ids).

Create a new file index.js under the user directory and update the following:

import Link from 'next/link';



function UserListComponentPage() {
  const users = [
    {id: "1", username: "User 1"},
    {id: "2", username: "User 2"},
    {id: "3", username: "User 3"}
  ];
  return (
    <div>
      <p> List of Users </p>
      <ul>
        {
          users.map(
            (user) => (
              <li key={user.id}>
                <Link href={`/user/${user.id}`}>{user.username}</Link>
              </li>
            )
          )
        }
      </ul>
    </div>
  )
}

export default UserListComponentPage;
Enter fullscreen mode Exit fullscreen mode

If you visit the URL http://localhost:3000/user, you will see the list of users. When you click on those links, it will load the respective components.

Setting Link Tag in Next.js way
Next.js provides an alternative way of setting the hrefs. We can define the pathname and then parameters (if any). In this case, replace

<Link href={`/user/${user.id}`}>{user.username}</Link>
Enter fullscreen mode Exit fullscreen mode

with

<Link href={  { 
       pathname: "/user/[userId]", 
         query: {userId: user.id }
  }} >
       {user.username}
 </Link>
Enter fullscreen mode Exit fullscreen mode

Visit the URL and you will see the same contents as before.

Top comments (0)