Understand How Does Routing Work In Next.js

In Next.js, routing works in a straightforward and intuitive manner. Next.js provides a file-based routing system, which means that the file structure within the “pages” directory determines the routes for your application.

Routing types in Next.js

File-Based Routing

In your Next.js project, the “pages” directory plays a crucial role in defining your routes. Each JavaScript file or component you create inside the “pages” directory represents a route in your application. For example:

  • The file “pages/index.js” represents the root route (“/”).The file “pages/about.js” represents the “/about” route.
You can create subdirectories within the “pages” directory to create nested routes. For example:
  • The file “pages/blog/index.js” represents the “/blog” route.The file “pages/blog/post.js” represents the “/blog/post” route.
The file and directory structure within the “pages” directory directly map to the URLs and routes of your application.

Dynamic Routes

Next.js allows you to create dynamic routes by using brackets (“[]”) in the file names. For example:

  • The file “pages/blog/[slug].js” represents a dynamic route where “slug” can be any value.The file “pages/users/[id].js” represents a dynamic route where “id” can be any value.
Dynamic routes enable you to handle varying URL parameters and generate dynamic content based on those parameters. Next.js provides a special hook called “getServerSideProps” or “getStaticProps” that allows you to fetch data for dynamic routes.

Link Component

Next.js provides a built-in “Link” component that you can use to navigate between pages. The “Link” component ensures that navigation happens without a full page reload, resulting in a smoother user experience. You can import the “Link” component from the “next/link” module and use it. When the user clicks on the “About” link, Next.js will handle the navigation and render the corresponding page without a full page refresh.

Programmatic Routing

Next.js also provides a “router” object that allows you to perform programmatic navigation. You can import the “useRouter” hook from the “next/router” module to access the router object and use methods like “push”, “replace”, or “back” to navigate programmatically.When the user clicks the button, the “handleClick” function triggers programmatic navigation to the “/about” route.

Next.js’s file-based routing system and the “Link” component make it easy to define and navigate between routes in your application. The routing mechanism seamlessly integrates with Next.js’s server-side rendering and static site generation capabilities, providing a powerful and efficient approach to building web applications.

Implementation

File Based Routing
  1. Create new nextjs app
npx create-next-app routing-example && cd routing-example
  1. Open in Visual studio code and create a folder src/pages. Then create page1.js, page2.js in src/pages
import React from 'react';

function page1(props) {
    return (
        <div>
            Page1
        </div>
    );
}

export default page1;
import React from 'react';

function page2(props) {
    return (
        <div>
            page2
        </div>
    );
}

export default page2;
  1. run the application and check http://localhost:3000/page1
npm run dev
Dyanmic Routing
  1. Create [blog].js file in src/pages
import { useRouter } from 'next/router';
import React from 'react';

function Blog() {
    const router = useRouter()
    return (
        <div>
            post: {router.query.blog}
        </div>
    );
}

export default Blog;
  1. Go to http://localhost:3000/2
  2. CatchAll – create [..slag].js file in src/pages/catchAll folder
import { useRouter } from 'next/router';
import React from 'react';

function Slag(props) {
    const router = useRouter()
    return (
        <div>
            passed params: {router.query.slag}
        </div>
    );
}

export default Slag;
Link Routing

Update the page1.js with below code to use link routing

import Link from 'next/link';
import { useRouter } from 'next/router';
import React from 'react';

function Page1(props) {
    const router = useRouter()
    return (
        <div>
            Page1
            <ul>
                <li>
                    <Link href="/">Home</Link>
                </li>
                <li>
                    <Link href="/about">one param dyanic link</Link>
                </li>
                <li>
                    <Link href="/catchAll/hello-world">Catch all</Link>
                </li>
            </ul>

 
        </div>
    );
}

export default Page1;
Programmatic Routing

Update the page1.js with below code to add programtic routing with a button click

Related Items:

How to use Next Js to create PWA

Leave a comment