Wednesday, November 27, 2024
Google search engine
HomeLanguagesNext.js Routing

Next.js Routing

Next.js is a full-stack React-based framework. Unlike a traditional react app, which loads and renders the entire application on the client, Next.js allows the first-page load to be rendered by the server, which is great for SEO and performance.

Some of the key features of Next.js are:

  • Server-side rendering
  • Image Optimization
  • Static Site generation
  • Easy Deployment

You can learn more about Next.js here. In this article, we will learn about routing in Next.js. Next.js has a file-based routing system. When a file is added to the page’s directory of our Next Project, it is treated as a route. The component exported as default from the files in the pages directory is rendered when we access that route. For instance, if we create a file called home.js in the pages directory, it will be treated as a route and can be accessed by visiting http://localhost:3000/home.

Types of Routes in Next.js: 

  • Index Routes: The index.js files in our pages directory are automatically routed to the root directory. For Example: If we create a file in the pages directory named index.js . Then it could be accessed by going to http://localhost:3000/
  • Nested Routes: If we create a nested folder structure, our routes will also be structured in the same manner. For Example:  If we create a new folder called users and create a new file called about.js within it, we can access this file by visiting http://localhost:3000/users/about
  • Dynamic Routes: We can also accept URL parameters and create dynamic routes using the bracket syntax. For Example: If we create a new page in the pages directory called [id].js then the component exported from this file, could access the parameter id and render content accordingly. This can be accessed by going to localhost:3000/<Any Dynamic Id> .

Linking between different routes: Next.js allows us to do client-side navigation using the Link component. It has a property called href that points to a known page.

Example: Let’s build a new Next Application to see the routing in action. Run the following command to create a new Next Application.

npx create-next-app myproject

When we open our app in a code editor we see the following project structure.

Project Structure: 

 

For the scope of this tutorial, we will only focus on the pages directory. When we initialize our Next App, we get a default index route. It works as a homepage for our application. Now we’ll set up three different routes to test all the route types in Next Js. 

Make a new folder called users in the pages directory called users, then make three new files in the user’s folder: [id].js, index.js, and about.js. We will also use the Link component to create navigation on our homepage to access these routes.

pages/index.js (http://localhost:3000/):  We’ll first start by cleaning up some boilerplate code in our pages/index.js file, and add three link components to access our routes.

Javascript




import React from "react";
import Link from "next/link";
const HomePage = () => {
  
  // This is id for dynamic route, you
  // can change it to any value.
  const id = 1;
  return (
    <>
      <h1>Home Page</h1>
      <ul>
        <li>
          <Link href="/users">
            <a>Users</a>
          </Link>
        </li>
        <li>
          <Link href="/users/about">
            <a>About Users</a>
          </Link>
        </li>
        <li>
          <Link href={`/users/${id}`}>
            <a>User with id {id}</a>
          </Link>
        </li>
      </ul>
    </>
  );
};
  
export default HomePage;


pages/users/index.js (http://localhost:3000/users): This is an index route hence router will automatically link to the root folder that is users.

Javascript




import React from 'react'
  
const Users = () => {
  return (
    <h1>Users Page</h1>
  )
}
  
export default Users


pages/users/about.js (http://localhost:3000/users/about): This is a nested route, we can nest our routes to any level based on our file structure.

Javascript




import React from 'react'
  
const Users = () => {
  return (
    <h1>Users About Page</h1>
  )
}
  
export default Users


pages/users/[id].js (http://localhost:3000/users/<id>): This is a dynamic route, and we can get to it by appending any dynamic id after users. This dynamic id could be accessed by the component using the useRouter hook provided by Next Js.

Javascript




import React from "react";
import { useRouter } from "next/router";
  
const User = () => {
  const router = useRouter();
  return <h1>User with id {router.query.id}</h1>;
};
  
export default User;


Step to run the application: Run your Next.js app using the following command: 

npm run dev

Output: 

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments