Next.js File Based Routing (Navigation) (Part-5)

Posted by Ashutosh on April 07, 2021




In our previous tutorials, 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;


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 (<a>). 


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;


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>
with 
<Link href={ { 
       pathname: "/user/[userId]", 
         query: {userId: user.id }
  }} >
       {user.username}
 </Link>


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