next js navigation to other page in a function

Next.js Navigation to Other Page in a Function

If you are using Next.js for your web development project, you might want to navigate to another page when a certain function is called. Fortunately, Next.js provides an easy-to-use router that allows you to do just that.

Using the Router Component

The easiest way to navigate to another page in Next.js is by using the built-in Router component. Here's an example:

import { useRouter } from 'next/router'

function handleClick() {
  const router = useRouter()
  router.push('/about')
}

function MyComponent() {
  return (
    <button onClick={handleClick}>
      Go to About Page
    </button>
  )
}

In this example, we import the useRouter hook from Next.js and use it to get a reference to the router object. We then call the push method of the router object to navigate to the '/about' page when the button is clicked.

If you want to navigate to another page using a link, you can use the Link component provided by Next.js. Here's an example:

<Link href="/about">
  <a>Go to About Page</a>
</Link>

In this example, we use the Link component to create a link to the '/about' page. When the link is clicked, Next.js will handle the navigation for us.

Using the Router Object Directly

If you need more control over the navigation process, you can use the router object directly. Here's an example:

import Router from 'next/router'

function handleClick() {
  Router.push({
    pathname: '/about',
    query: { name: 'Raju' },
  })
}

function MyComponent() {
  return (
    <button onClick={handleClick}>
      Go to About Page
    </button>
  )
}

In this example, we import the Router object from Next.js and use it to navigate to the '/about' page with a query parameter. We pass an object with two properties to the push method of the Router object. The pathname property specifies the path of the page we want to navigate to, and the query property specifies any query parameters we want to include.

Conclusion

In this article, we've looked at three different ways to navigate to another page in Next.js. Whether you prefer to use the Router component, the Link component, or the router object directly, Next.js provides a simple and flexible way to handle navigation in your web application.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe