Routing in Next.js

In next.js, the file system enables routing in the application. It automatically treats every file with the extensions .js, .jsx, .ts, or .tsx under the pages directory as a route.

Working of the Next.js Routing
Next.js uses a file system based routing for creating a new route. Each Next.js project has a pages folder. Every file and folder inside the pages folder is considered a route.
In the pages folder, the first root route is index.js which renders on the / path. Also, we can create nested routes by creating a folder inside the pages directory.

Let us consider the following example :

Here we have five pages.

  • index.js maps to the path /.
  • px.js maps to the path /px.
  • careers.js maps to the path /careers.
  • reactBlog.js is in the sub folder, and we can access it on path /blogs/reactBlog.
  • We can access nextjsBlog.js on path /blogs/nextjsBlog.

Types of Routing in Next.js
Next.js has three types of routes

  • Index Route
  • Nested Route
  • Dynamic Route

Index Route
In the pages directory, we have the index.js file, which is automatically routed to the root folder.

Example :

Here we created a file in the pages folder named index.js, it could be accessed using  /. Inside the pages directory, we have a blog folder containing an index.js file. It would be accessible on /blog.

Nested Route
Nested routes allow you to create a route inside the parent component. If we created nested folders in the pages directory, then routes will be nested.

Example:

we created a new folder blog with a routing-in-nextjs.js file in it, we can access this page by visiting blog/routing-in-nextjs.

Dynamic Route
Next.js can accept URL parameters and create dynamic routes using the bracket syntax.


Example:
If we create a new page in the pages directory called [username].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/<username>.

Accessing router in React components

To access the router object inside the react components, we have to use the useRouter() hook or withRouter.
The following example shows us how to access the router in react component.

 

 import React from 'react'
import { useRouter } from 'next/router'



 export default function Page() {
  const router = useRouter()
  return (
    <button type="button" onClick={() => router.push(‘/px’)}>
      Px
    </button>
  )
}


Next/Router Methods
The router object provides the following methods:


router.push()
It handles the client-side transitions.
Syntax :

router.push(url, as, options)

url is the route of the new state.

as is the url to be shown in a browser.

options is the optional object sent by the router.push().
options can be -
Scroll - controls the scrolling to the top page. By default, it is true.

Locale - denotes the locale of a new page.

Example:

import { useRouter } from 'next/router'

export default function SoftwareDevelopmentButton() {
const router = useRouter()

return (
  <button type="button" onClick={() =>
      router.push('/softwareDevelopment','/software-development', {scroll: false})}>
    Software Development
  </button>
)
}

router.replace()

router.replace() prevent adding new entry in history stack.
Syntax :

router.replace(url, as, options)

Example:

import { useRouter } from 'next/router'

export default function SoftwareDevelopmentButton() {
const router = useRouter()

return (
  <button type="button" onClick={() => router.replace('/software-development')}>
    Software Development
  </button>
)
}

router.back()
It navigates back to history. It behaves similar to the browser back button. It executes windows.history.back().


Example:

import { useRouter } from 'next/router'

export default function GoBackButton() {
const router = useRouter()

return (
  <button type="button" onClick={() => router.back()}>
    Go back
  </button>
)
}

router.reload()

It reloads the current page. It behaves similar to the browser's refresh button. It executes windows.location.reload().


Example:

export default function ReloadButton() {
const router = useRouter()

return (
  <button type="button" onClick={() => router.reload()}>
    Reload

   </button>
)
}

router.prefetch() :

It prefetch pages for faster client-side transitions. It is only helpful for navigations without next/link, as next/link takes care of prefetching pages automatically.
Note: This is only a production-only feature.
Syntax:

router.prefetch(url, as)

Conclusion :
We have quickly gone over the next/router, and it's working. Then, we saw routing types and their examples. We learned how to inject router in react components and some router methods with examples.

Dnyaneshwari Abuj

Dnyaneshwari Abuj

Beed.