useRouter in NextJs

|
| By Sonali Sharma

Routing –

The file-system-based router in Next.js is based on the idea of pages. A file becomes immediately accessible as a route when it is added to the page’s directory. The majority of typical patterns can be defined using the files in the pages directory.

Two approaches to routing are available:

  • next/link – The Next.js router enables client-side route transitions between pages, much like a single-page application.
  • next/router – Use useRouter or withRouter to access the router object

useRouter

This method is used to handle client-side transitions where the next/link is not enough. Mainly we use this method on JS events.
UseRouter cannot be used with classes because it is a React Hook. Depending on the situation, either use withRouter or wrap your class with a function component. The two useRouter techniques are explained below.

router.push – Navigating to pages/about.js, which is a predefined route:
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/about')}>
Click me
</button>
)
}

With URL object
You can use a URL object in the same way you can use it for next/link. Works for both the URL and as parameters:
import { useRouter } from 'next/router'
export default function Page({ post }) {
const router = useRouter()
return (
<button
type="button"
onClick={() => {
router.push({
pathname: '/post/[pid]',
query: { pid: post.id },
})
}}
>
Click here </button>
)
}

router.replace

Routing.replace will stop adding a new URL entry to the history stack.

router.replace(url, as, options)

Using router.replace in code –
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.replace('/home')}>
Click me
</button>
)
}

Leave a Reply

Your email address will not be published. Required fields are marked *