Friday, November 22, 2024
Google search engine
HomeLanguagesHow to get current route in Next.js ?

How to get current route in Next.js ?

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.

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.

In this article, we are going to look into 3 methods to get the current route in NextJs.

  • Using useRouter().
  • Using withRouter().
  • Using Context prop in getInitialProps.

Let’s understand all three methods with the implementation.

Method 1: Using useRouter() Method: In NextJs we can easily get the value of the current route using the useRouter() function. To use this we are going to create a new page inside our pages directory with the name ‘get-route.js‘. After that, we will add the below code in our get-route.js page. In the below code first, we are importing our useRouter function from the next/router after that we are creating a new function with the name of getRoute and inside that, we are calling our useRouter() and storing that variable in a new constant variable named router. After that, we are displaying the pathname, asPath, and query from the route variable.

Javascript




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


Step to run the application: Start the development server by typing the below command in the terminal.

npm run dev

Output:

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.

But useRouter() is a react hook so if you use this inside a class component and this will give an error. So if we change our getRoute() function to a class with the same content then we will get the following output.

In the below code we are just changing our function to a class component.

Javascript




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


Step to run the application: Start the development server by typing the below command in the terminal.

npm run dev

Output:

So to fix this we can use withRouter().

Method 2: Using withRouter() Method: You can easily get the current router value in react class component using the withRouter(). To use this you just have to export your class component inside withRouter(). In the below code first, we are importing our withRouter function from the next/router after that we are creating a new class component with the name of getRoute and inside that, In our render function, we are displaying the pathname, asPath, and query from the props received in our class. After that, we are exporting our class u=inside withRouter() function.

Javascript




import React from 'react'
import {withRouter} from 'next/router';
  
export class getRoute extends React.Component {
      
    render() {
        console.log(this.props.router.pathname)
        console.log(this.props.router.query)
        console.log(this.props.router.asPath)
        return (
            <div>
                <h1>neveropen</h1>
                <h2>Using withRouter</h2>
            </div>
        )
    }
}
  
export default withRouter(getRoute)


Step to run the application: Start the development server by typing the below command in the terminal.

npm run dev

Output:

 

Method 3: Using getInitialProps() Method: You can also access the value of the route the context prop inside getInitialProps(). Context prop contains information of your routes like asPath, query, and Pathname. In the below code first, we are importing our withRouter function from the next/router after that we are creating a new class component with the name of getRoute and inside that, we are creating a async getIntitalProps function which contains context as a prop. Then we are storing values of context in a new variableand returning them. Then in our render function, we are displaying the pathname, asPath, and query from the props received in our class. 

Javascript




import React from 'react'
import {withRouter} from 'next/router';
  
export class getRoute extends React.Component {
  
    static async getInitialProps(context) {
        // Using context prop to get asPath, query, context
        const {asPath, query, pathname} = context 
        return{asPath, query, pathname}
    }
      
    render() {
        // Consoling the values
        console.log(this.props.pathname)
        console.log(this.props.query)
        console.log(this.props.asPath)
        return (
            <div>
                <h1>neveropen</h1>
                <h2>Using Context prop in getInitialProps</h2>
            </div>
        )
    }
}
  
export default getRoute


Step to run the application: 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