How to programmatically navigate in Next.js

Last updated on January 14, 2021 A Goodman Loading... Post a comment

Next.js is a fast-growing React framework that can help us build high-performance hybrid static and server-side rendering web applications. Many projects have been transitioning from traditional React SPAs to Next.js, including giants like Github, IGN, Hulu, etc.

In this article, we’ll explore how to programmatically navigate in a Next.js application by using the useRouter hook that comes along with Next.js core. This will be helpful in some scenarios like changing routes when the user clicks a button, checks a checkbox, chooses an option from a dropdown select menu, after waiting for a countdown timer.

useReducer hook

Simple usage:

import { useRouter } from 'next/router';

export default function Home() {
  const router = useRouter();
  console.log(router);
  return <></>;
}

The router object returned by the useRouter hook gives us some useful methods for programmatically navigating:

push() method

Syntax:

push(url, as, options)

Where:

  • url: The URL to navigate to
  • as: Optional decorator for the URL that will be shown in the browser
  • options: Optional object with the following configuration options:
    • shallow: Update the path of the current page without rerunning getStaticProps, getServerSideProps, or getInitialProps. Defaults to false.

replace() method

This method is similar to the push() method but will NOT add a new URL into the history stack. That means you cannot go back to the previous route by hitting the back button of your browser.

Syntax:

router.replace(url, as, options)

The Complete Example

This example demonstrates how to navigate in Next.js by clicking a button or checking a checkbox.

Preview

Our sample app has 2 only pages: Home and Feedback.

The code

Create a new file in your pages folder named feedback.js and add the following:

const FeedBack = props => {
  return <div style={{padding: 50}}>
    <h1>Feedback Page</h1>
  </div>
}

export default FeedBack;

And here’s the code in the index.js:

import { useRouter } from 'next/router';

export default function Home() {
  const router = useRouter();
  return (
    <div style={{ padding: 50 }}>
      <h1>Home Page</h1>
      <h2>push()</h2>
      <p>
        <button onClick={() => router.push('/feedback')}>
          Go to the feedback page
        </button>
      </p>
      <p>
        <input
          type="checkbox"
          onChange={() => router.push('/feedback')}
        ></input> Check me to go to the feedback page
      </p>
      <br />

      <h2>replace()</h2>
      <div>
        <button onClick={() => router.replace('/feedback')}>
          Go to the feedback page and not go back
        </button>
      </div>
    </div>
  );
}

Wrap Up

n this article, you learned a lot about the useRouter hook in Next.js. Thanks to it, we can navigate between routes in more ways than just using next / link.

If you would like to learn more about Next.js, take a look at one of the following articles: How to use Ant Design in a Next.js projectNext.js: 404 error page and 404 error codeHow to add Favicon to a Next.js app, or check out our Next.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles