Sunday, December 29, 2024
Google search engine
HomeLanguagesNext.js Dynamic Route Segments

Next.js Dynamic Route Segments

In this article, we will learn How we can get the current route in our NextJS project.

NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.

Dynamic route segments are dynamic routes (a.k.a. url slugs, pretty urls, and others) that we can create in NextJs apps using the brackets in the name of the file. This will help developers to create more complex apps which will be difficult to create only with predefined paths.

Create NextJS Application: You can create a new NextJs project using the below command:

npx create-next-app gfg

Project Structure: It will look like this.

NextJs allows the feature to create dynamic routes without much effort. You can follow the below steps to create dynamic routes.

Step 1: Create a new folder with the name of ‘dynamic’ and inside that folder create a dynamic route. We can create dynamic routes in NextJs by using square brackets in the name of the file. For example:-

/pages/route/[file_name].js

Step 2: Create a dynamic route file with the name ‘[data] .js‘ and add the below content in the file.

Javascript




import React from 'react'
import {useRouter} from 'next/router';
  
export default function getRoute() {
    // Calling useRouter() hook
    const router = useRouter()
    console.log(router.query)
    return (
        <div>
            <h1>neveropen</h1>
            <h2>pathname:- {router.pathname}</h2>
            <h2>asPath:- {router.asPath}</h2>
        </div>
    )
}


In the above example first, we are calling our useRouter() hook and after that, we are displaying the objects of our router in the console.

  • pathname:  Current route. That is the path of the page in ‘/pages’.
  • query: The query string parsed to an object.
  • asPath: The path (including the query) shown in the browser.

Step 3: Start the development server by typing the below command in the terminal.

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